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

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) ;}}

相关文章:

  • python基于Django+mysql实现的图书管理系统【完整源码+数据库】
  • Oracle数据库文件变成32k故障恢复--惜分飞
  • linux dts overlay
  • [1-01-01].第27节:常用类 - 包装类
  • 大模型证书
  • 16.2 Docker多阶段构建实战:LanguageMentor镜像瘦身40%,支持500+并发1.2秒响应!
  • LLaMA-Factory 对 omnisql 进行 ppo dpo grpo nl2sql任务 实现难度 时间 全面对比
  • 系统学习 Android 的 进程管理、内存管理、音频管理
  • 虚拟机远程连接编译部署QT程序
  • canvas面试题200道
  • 霸王餐系统
  • 数据源简单配置应用
  • GO 语言学习 之 语句块
  • 第N5周:Pytorch文本分类入门
  • Windows11系统上安装WM虚拟机及Ubuntu 22.04系统
  • 地址簇与数据序列
  • SpringCloud系列(38)--SpringCloud Gateway实现动态路由
  • SYSCFG 时钟在 GD32F4 系列微控制器中的作用
  • 升级 PowerShell 7
  • elastic-ai.creator开源程序是设计、训练和生成专门针对 FPGA 优化的神经网络