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

本文介绍了如何在ASP.NETCore应用中使用Polly库实现HTTP请求的自动重试功能,当请求失败时,通过`asyncRetryPolicy`执行5次重试,确保服务的稳定性和连续性。
摘要由CSDN通过智能技术生成

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("请求失败");
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值