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

相关推荐

  1. .net 服务 服务保护 自动 Polly

    2024-02-21 11:04:03       54 阅读
  2. Sentinel服务保护

    2024-02-21 11:04:03       53 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-21 11:04:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-21 11:04:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-21 11:04:03       87 阅读
  4. Python语言-面向对象

    2024-02-21 11:04:03       96 阅读

热门阅读

  1. C++ 中的单例模式singleton

    2024-02-21 11:04:03       47 阅读
  2. 设计模式----单例模式

    2024-02-21 11:04:03       45 阅读
  3. 指定截至频率的低通滤波器设计

    2024-02-21 11:04:03       49 阅读
  4. 小程序缓存封装 storage

    2024-02-21 11:04:03       52 阅读
  5. k8s 基础理论

    2024-02-21 11:04:03       42 阅读
  6. 线程相关整理

    2024-02-21 11:04:03       48 阅读
  7. 深度神经网络

    2024-02-21 11:04:03       55 阅读