.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("请求失败");
        }
相关推荐
云中小生4 小时前
ASP.NET Core MVC修仙指南
.net
步、步、为营1 天前
.NET 如何实现ChatGPT的Stream传输
chatgpt·.net
喵叔哟1 天前
37.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--扩展功能--增加Github Action
微服务·github·.net
步、步、为营1 天前
.NET8 正式发布, C#12 新变化
ui·c#·.net
伽蓝_游戏1 天前
Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(7)
游戏·ui·unity·架构·c#·游戏引擎·.net
追逐时光者2 天前
一款基于 .NET + Vue 编写的仿钉钉的开源低代码工作流引擎,支持多种数据库,开箱即用!
后端·.net
CodeCraft Studio2 天前
使用 Aspose.OCR 将图像文本转换为可编辑文本
java·人工智能·python·ocr·.net·aspose·ocr工具
Kookoos2 天前
ABP VNext + Quartz.NET vs Hangfire:灵活调度与任务管理
c#·.net·hangfire·quartz.net·abp vnext
时光追逐者2 天前
C#/.NET/.NET Core优秀项目和框架2025年7月简报
c#·.net·.netcore
伽蓝_游戏3 天前
Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(6)
游戏·ui·unity·架构·c#·游戏引擎·.net