.net 微服务 服务保护 自动重试 Polly

1. 概要

实验服务保护,自动重新连接功能。

2.代码

2.1 重复工具

复制代码
using Polly;
using Polly.Retry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApplication2
{
    public class ClientPolicy
    {
        public AsyncRetryPolicy<HttpResponseMessage> asyncRetryPolicy { get; set; } 
        public ClientPolicy()
        {
            asyncRetryPolicy = Policy.HandleResult<HttpResponseMessage>(p=>!p.IsSuccessStatusCode).WaitAndRetryAsync(5,retryAttemp=>TimeSpan.FromSeconds(Math.Pow(2,retryAttemp)));
        }
    }
}

2.2 调用位置

复制代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApplication2.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            ClientPolicy clientPolicy = new ClientPolicy();
            HttpClient httpClient = new HttpClient();
            clientPolicy.asyncRetryPolicy.ExecuteAsync(() => httpClient.GetAsync($"https://localhost:44367/test"));


            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet("/test")]
        public IActionResult test()
        {
            var randomNumber = new Random().Next(1, 100);
            if(randomNumber > 20)
            {
                //Console.WriteLine("请求成功 200");
                //return Ok("请求成功");
            }
            Console.WriteLine("请求失败");
            return BadRequest("请求失败");
        }
    }
}

2.实验结果

如果失败下面的函数会重复调用5次

复制代码
[HttpGet("/test")]
        public IActionResult test()
        {
            var randomNumber = new Random().Next(1, 100);
            if(randomNumber > 20)
            {
                //Console.WriteLine("请求成功 200");
                //return Ok("请求成功");
            }
            Console.WriteLine("请求失败");
            return BadRequest("请求失败");
        }
相关推荐
AlphaNil1 小时前
.NET + AI 跨平台实战系列(三):云端多模态API实战——用GPT-4V让App看懂世界
人工智能·后端·.net·maui
专注VB编程开发20年2 小时前
“机械臂写字”最完美的开源数据源之一
.net
缺点内向4 小时前
C#实战:使用Spire.XLS for .NET 将Excel转换为SVG图片
c#·自动化·.net·excel
我是唐青枫4 小时前
C#.NET Channel 深入解析:高性能异步生产者消费者模型实战
开发语言·c#·.net
Crazy Struggle4 小时前
C# + ViewFaceCore 快速实现高精度人脸识别
c#·人脸识别·.net·开源项目
AlphaNil8 小时前
.NET + AI 跨平台实战系列(五):构建智能相册核心功能——批量处理与本地缓存
人工智能·后端·.net·maui
AlphaNil8 小时前
.NET + AI 跨平台实战系列(四):本地化部署——使用Ollama运行开源多模态模型
人工智能·开源·.net
The Shio9 小时前
为什么我认为设备协议真正缺的,不是更多文档,而是代码生成能力?
网络·物联网·c#·.net·业界资讯
唐青枫12 小时前
C#.NET Span 深入解析:零拷贝内存切片与高性能实战
c#·.net
步步为营DotNet1 天前
深入理解ASP.NET Core Middleware:构建高效Web应用的关键组件
中间件·asp.net·.net