.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("请求失败");
        }
相关推荐
你有哈莫吗11 分钟前
记一次 .NET 某自动化智能制造软件 卡死分析
自动化·.net·制造
水瓶夜之2 小时前
.NET 中的新增功能系列文章——.NET SDK中的新增功能
前端·chrome·.net
布鲁飞丝2 小时前
对 .NET线程 异常退出引发程序崩溃的反思
数据库·c#·.net
geovindu3 小时前
CSharp: LogHelper
开发语言·后端·c#·.net
何解忧16 小时前
.NET 中的新增功能系列文章—— .NET MAUI 中的新增功能
.net
仙宇觉尘19 小时前
一款基于 .NET 开源美观、功能丰富的串口调试工具
开源·.net
仙宇觉尘1 天前
记一次 .NET 某中医药附属医院门诊系统 崩溃分析
数据库·oracle·.net
丙氨酸長鏈1 天前
关于.net发布单体exe程序无法打开问题详解
.net
鲜花飘飘扬1 天前
C# 与 .NET 跨平台开发实战(第一章:开发环境搭建与.NET概述-上篇)
开发语言·c#·.net
风样滴男人哟1 天前
基于 .NET 开源、功能齐全的分布式作业调度系统
分布式·开源·.net