当前位置: 首页 > news >正文

.net 写了一个支持重试、熔断和超时策略的 HttpClient 实例池

public class HttpClientPool : IDisposable
{private readonly ConcurrentQueue<HttpClient> _httpClientPool; // HttpClient 对象池private readonly SemaphoreSlim _semaphore; // 控制同时访问 HttpClient 对象池的线程数private readonly TimeSpan _timeout; // 获取 HttpClient 的超时时间private readonly int _maxRetries; // 最大重试次数private readonly TimeSpan _circuitBreakerTimeout; // 熔断器超时时间private readonly int _consecutiveFailuresThreshold; // 连续失败阈值private bool _circuitBreakerTripped; // 熔断器是否触发private DateTime _circuitBreakerTrippedTime; // 熔断器触发时间private int _consecutiveFailures; // 连续失败计数器public HttpClientPool(int maxPoolSize, // 最大 HttpClient 对象池大小TimeSpan timeout, // 获取 HttpClient 的超时时间int maxRetries, // 最大重试次数TimeSpan circuitBreakerTimeout, // 熔断器超时时间int consecutiveFailuresThreshold // 连续失败阈值){_httpClientPool = new ConcurrentQueue<HttpClient>();_semaphore = new SemaphoreSlim(maxPoolSize);_timeout = timeout;_maxRetries = maxRetries;_circuitBreakerTimeout = circuitBreakerTimeout;_consecutiveFailuresThreshold = consecutiveFailuresThreshold;_circuitBreakerTripped = false;}public async Task<HttpResponseMessage> SendRequestWithRetries(string url){var retryCount = 0;_consecutiveFailures = 0;while (retryCount <= _maxRetries){try{var httpClient = await GetHttpClientAsync();var response = await httpClient.GetAsync(url);if (response.IsSuccessStatusCode){_consecutiveFailures = 0; // 重置连续失败计数器return response;}else{_consecutiveFailures++;if (_consecutiveFailures >= _consecutiveFailuresThreshold){TripCircuitBreaker(); // 连续失败达到阈值,触发熔断器throw new InvalidOperationException("连续失败次数达到阈值,熔断器已触发。");}retryCount++;}}catch (Exception ex){_consecutiveFailures++;if (_consecutiveFailures >= _consecutiveFailuresThreshold){TripCircuitBreaker(); // 连续失败达到阈值,触发熔断器throw new InvalidOperationException("连续失败次数达到阈值,熔断器已触发。");}retryCount++;}}throw new Exception($"重试 {_maxRetries} 次后仍然无法发送请求。");}private async Task<HttpClient> GetHttpClientAsync(){if (_circuitBreakerTripped){var elapsedTime = DateTime.Now - _circuitBreakerTrippedTime;if (elapsedTime < _circuitBreakerTimeout){throw new InvalidOperationException("熔断器已触发,请稍后重试。");}else{// 重置熔断器_circuitBreakerTripped = false;}}if (await _semaphore.WaitAsync(_timeout)){if (_httpClientPool.TryDequeue(out var httpClient)){return httpClient;}}throw new TimeoutException("获取 HttpClient 超时。");}public void ReturnHttpClient(HttpClient httpClient, bool success){if (success){_httpClientPool.Enqueue(httpClient);_semaphore.Release();}else{// 触发熔断器TripCircuitBreaker();httpClient.Dispose();_semaphore.Release();}}private void TripCircuitBreaker(){_circuitBreakerTripped = true;_circuitBreakerTrippedTime = DateTime.Now;_consecutiveFailures = 0;}public void Dispose(){foreach (var httpClient in _httpClientPool){httpClient.Dispose();}_httpClientPool.Clear();_semaphore.Dispose();}
}

调用端
 

public class Program
{public static async Task Main(){// 创建 HttpClientPoolvar httpClientPool = new HttpClientPool(maxPoolSize: 10,timeout: TimeSpan.FromSeconds(5),maxRetries: 3,circuitBreakerTimeout: TimeSpan.FromMinutes(10),consecutiveFailuresThreshold: 5);try{var response = await httpClientPool.SendRequestWithRetries("https://api.example.com");var content = await response.Content.ReadAsStringAsync();Console.WriteLine(content);}catch (Exception ex){Console.WriteLine($"请求失败:{ex.Message}");}}
}

http://www.lryc.cn/news/216402.html

相关文章:

  • 大促期间如何监测竞品数据
  • Linux yum 没有可用软件包 fping。 错误:无须任何处理 的解决办法
  • 人工智能与脑机接口:开启人机融合的新时代
  • 【多线程面试题二十二】、 说说你对读写锁的了解
  • Panda3d 相机控制
  • Linux(CentOS)安装MySQL教程
  • 使用 OpenSSL 工具撰写 Bash 脚本进行密码明文的加密与解密
  • uniapp之actionsheet 自定义组件
  • 在nodejs中使用Mongoose和MongoDB实现curd操作
  • 10.28 校招 实习 内推 面经
  • Azure 机器学习 - 使用无代码 AutoML 训练分类模型
  • 【调试技术】用户态查看PEB和TEB
  • 如何搭建一个Spring MVC和Vue3的应用程序
  • CSS3设计动画样式
  • AtCoder abc 144
  • 【开题报告】基于SpringBoot的医美在线预约系统的设计与实现
  • AutoGen agent使用;调用本地LLM
  • Docker安装matomo
  • 副对角线以上和以下都为0的行列式求解
  • DSP开发例程(4): logbuf_print_to_uart
  • 计算机毕业设计选题推荐-超市售货微信小程序/安卓APP-项目实战
  • Azure 机器学习 - 使用 Visual Studio Code训练图像分类 TensorFlow 模型
  • Vue 创建自定义 ref 函数
  • [2016-2018]phpstudy的exp制作
  • 服务器数据恢复—Zfs文件系统下文件被误删除的如何恢复数据?
  • 关于嵌入式rtthread系统与单片机芯片
  • 在Ubuntu上安装Redis并学习使用get、set和keys命令
  • Ubuntu更换镜像源
  • Sulfo-CY5 NHS荧光染料的生物应用2230212-27-6星戈瑞
  • Python Django 之模板继承详解(extends)