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

OkHttp 简单配置

OkHttpClient 的简单配置,包含重试,线程池
@Configuration
public class OkHttpConfig {@Bean("deSourceOkHttp")public OkHttpClient okHttpClient() {return new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).addInterceptor(new SmartRetryInterceptor(3,1000,true)).connectionPool(new ConnectionPool(50, 1, TimeUnit.MINUTES)).addInterceptor(chain -> chain.proceed(chain.request().newBuilder().addHeader("Accept", "application/json").addHeader("Content-Type", "application/json").build())).build();}
}

重试

public class SmartRetryInterceptor implements Interceptor {private final int maxRetries;private final long baseDelayMs;private final boolean enableJitter;public SmartRetryInterceptor(int maxRetries, long baseDelayMs, boolean enableJitter) {this.maxRetries = maxRetries;this.baseDelayMs = baseDelayMs;this.enableJitter = enableJitter;}@Overridepublic Response intercept(Chain chain) throws IOException {Request request = chain.request();Response response = null;IOException exception = null;for (int i = 0; i <= maxRetries; i++) {try {response = chain.proceed(request);if (isSuccessfulOrShouldNotRetry(response)) {return response;}} catch (IOException e) {exception = e;}// 如果是幂等请求或满足特定条件,才重试if (isIdempotent(request) && i < maxRetries) {long delay = baseDelayMs * (1 << i); // 指数退避if (enableJitter) {delay += new Random().nextInt((int) (baseDelayMs * 0.5));}try {Thread.sleep(delay);} catch (InterruptedException e) {Thread.currentThread().interrupt();throw new IOException("重试中断", e);}} else {break;}}if (response != null) {return response;}throw exception;}private boolean isSuccessfulOrShouldNotRetry(Response response) {return response.isSuccessful() || !shouldRetry(response.code());}private boolean shouldRetry(int code) {return retryhttpCpde.containsKey(code);}private boolean isIdempotent(Request request) {String method = request.method();return "GET".equals(method) || "POST".equals(method) ;}}

http://www.xdnf.cn/news/14657.html

相关文章:

  • 链表题解——两数相加【LeetCode】
  • .NET MAUI跨平台串口通讯方案
  • 永磁无刷电机旋转原理
  • 架构轻巧的kokoro 文本转语音模型
  • Apipost 和 Apifox 2025最新功能对比分析
  • 2-深度学习挖短线股-1-股票范围选择
  • [3D-portfolio] 版块包装高阶组件(封装到HOC) | Email表单逻辑 | 链式调用
  • 桌面小屏幕实战课程:DesktopScreen 11 SPI 水墨屏
  • 基于SpringBoot和Leaflet的区域冲突可视化-以伊以冲突为例
  • Robyn高性能Web框架系列06:使用WebSocket实现产品智能助理
  • SQL学习笔记3
  • 图像质量对比感悟
  • 智表ZCELL产品V3.2 版发布,新增拖动调整行列功能,修复了插件引用相对路径等问题
  • 【C++11】右值引用和移动语义
  • Hive3.1.3加载paimon-hive-connector-3.1-1.1.1.jar报错UnsatisfiedLinkError
  • 解决uniapp vue3版本封装组件后:deep()样式穿透不生效的问题
  • 【攻防篇】解决:阿里云docker 容器中自动启动xmrig挖矿
  • 超实用AI工具分享——ViiTor AI视频配音功能教程(附图文)
  • php项目部署----------酒店项目
  • 知攻善防应急靶机 Windows web 3
  • LVS-DR负载均衡群集深度实践:高性能架构设计与排障指南
  • 笔记02:布线-差分对的设置与添加
  • Liunx操作系统笔记2
  • 《解锁前端潜力:自动化流程搭建秘籍》
  • Boosting:从理论到实践——集成学习中的偏差征服者
  • linux-修改文件命令(补充)
  • Jenkins Pipeline 与 Python 脚本之间使用环境变量通信
  • 数的三次方根
  • 【深度学习新浪潮】空间计算的医疗应用技术分析(简要版)
  • TCP/UDP协议深度解析(二):TCP连接管理全解,三次握手四次挥手的完整流程