Polly服务熔断
//自定义异常 public class MyException : Exception { public MyException(string? message) : base(message) { } } public class CircuitBreakerExample { //熔断规则 private static readonly IAsyncPolicy<HttpResponseMessage> _circuitBreakerPolicy = Policy<HttpResponseMessage> .Handle<MyException>() // 可以指定更具体>的异常类型 .OrResult(resopnse=>resopnse.StatusCode==HttpStatusCode.InternalServerError) .CircuitBreakerAsync( handledEventsAllowedBeforeBreaking: 5, // 在断路器跳闸前允许通过的失败事件数(连续失败的次数) durationOfBreak: TimeSpan.FromSeconds(3), // 断路器跳闸后保持打开的时间 onBreak: (ex, breakTimeout) => // 当断路器跳闸时执行的回调 { Console.WriteLine("熔断开关状态为open, 服务" + breakTimeout.TotalSeconds + " 秒后才能再次访问"); }, onReset: () => // 当断路器从跳闸状态恢复时执行的回调 { Console.WriteLine("熔断开关状态为closed,现在能再次访问服务"); }, onHalfOpen: () => // 当断路器从关闭状态变为半开状态时执行的回调 { Console.WriteLine("熔断开关现在状态为 half-open。允许单次呼叫查看服务是否可用."); } ); //通过熔断规则调用服务 public static async Task CallServiceWithCircuitBreakerAsync() { try { // 使用断路器策略来调用服务 await _circuitBreakerPolicy.ExecuteAsync(RemoteService); } //捕获断路异常 catch (BrokenCircuitException ex) { Console.WriteLine("熔断开关状态为open"); } } //模拟远程服务 private static int FailCount = 6; public static async Task<HttpResponseMessage> RemoteService() { try { await Task.Delay(100); if (FailCount == 0) { Console.WriteLine("请求服务成功!"); return new HttpResponseMessage(System.Net.HttpStatusCode.OK); } // 模拟成功的服务响应 FailCount = FailCount - 1; throw new MyException("请求服务失败!"); } catch { Console.WriteLine("请求服务失败!"); return new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError); } } }
#region Polly熔断服务 #if true await Task.Run(async () => { while (true) { await Task.Delay(1000); CircuitBreakerExample.CallServiceWithCircuitBreakerAsync().Wait(); } }); #endif #endregion
喜欢 C#、SQL、Web