1. 概要
實(shí)驗(yàn)服務(wù)保護(hù),自動(dòng)重新連接功能。
2.代碼
2.1 重復(fù)工具?
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 調(diào)用位置
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("請(qǐng)求成功 200");
//return Ok("請(qǐng)求成功");
}
Console.WriteLine("請(qǐng)求失敗");
return BadRequest("請(qǐng)求失敗");
}
}
}
2.實(shí)驗(yàn)結(jié)果文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-833528.html
如果失敗下面的函數(shù)會(huì)重復(fù)調(diào)用5次文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-833528.html
[HttpGet("/test")]
public IActionResult test()
{
var randomNumber = new Random().Next(1, 100);
if(randomNumber > 20)
{
//Console.WriteLine("請(qǐng)求成功 200");
//return Ok("請(qǐng)求成功");
}
Console.WriteLine("請(qǐng)求失敗");
return BadRequest("請(qǐng)求失敗");
}
到了這里,關(guān)于.net 微服務(wù) 服務(wù)保護(hù) 自動(dòng)重試 Polly的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!