OKHTTP自动次数重试方案与连接池

连接池

最近在工作中开始使用okhttp,详细的研究了一下源码,发现了关于连接池的部分与我之前的理解有些不符

new OkHttpClient().newBuilder().connectionPool(new ConnectionPool(100,1,TimeUnit.MILLISECONDS))

使用过okhttp的人都知道在构建client的时候就声明了连接池

new ConnectionPool(100,1,TimeUnit.MILLISECONDS)

maxIdleConnections:最大空闲连接池数据量

keepAliveDuration: 连接的存活时间

timeUnit:时间单位

作为一个线程池应该有coreSize,MaxSize,queue的啊?仔细的看了一下源码okhttp3.internal.connection.RealConnectionPool

中,内部的执行线程池其实是:

private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
      Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
      new SynchronousQueue<>(), Util.threadFactory("OkHttp ConnectionPool", true));

是一个无限大的线程池,而那三个参数其实是回收线程的触发条件,就是说如果有线程超过了keepAlive设置的时间或者超过了maxldleConnections的数量就会触发回收

private final Runnable cleanupRunnable = () -> {
    while (true) {
      long waitNanos = cleanup(System.nanoTime());
      if (waitNanos == -1) return;
      if (waitNanos > 0) {
        long waitMillis = waitNanos / 1000000L;
        waitNanos -= (waitMillis * 1000000L);
        synchronized (RealConnectionPool.this) {
          try {
            RealConnectionPool.this.wait(waitMillis, (int) waitNanos);
          } catch (InterruptedException ignored) {
          }
        }
      }
    }
  };

自动重试次数方案

由于网络抖动可能会产生大量的网络断链,所以httpClient自动重试是非常有必要的。

仔细的看了看okhttp3.RealCall

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(new RetryAndFollowUpInterceptor(client));
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

    Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,
        originalRequest, this, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    boolean calledNoMoreExchanges = false;
    try {
      Response response = chain.proceed(originalRequest);
      if (transmitter.isCanceled()) {
        closeQuietly(response);
        throw new IOException("Canceled");
      }
      return response;
    } catch (IOException e) {
      calledNoMoreExchanges = true;
      throw transmitter.noMoreExchanges(e);
    } finally {
      if (!calledNoMoreExchanges) {
        transmitter.noMoreExchanges(null);
      }
    }
  }

内部实现是使用一个又一个的interceptor来完成一个http请求的,(无意中发现了interceptors和networkInterceptors的区别)

责任链设计模式。

调用顺序是:RetryAndFollowUpInterceptor》BridgeInterceptor〉CacheInterceptor》ConnectInterceptor〉CallServerInterceptor

想要实现自动重试我把注意力放到了RetryAndFollowUpInterceptor中毕竟单看名字就很像,最开始我的方案是仿照它自己实现一个interceptor放在它之前,过程不不必缀诉最终没有实现。

这里有一个配置参数retryOnConnectionFailure在连接失败的时候

想要实现自定义自动重试次数只能想其他的办法了,我把注意力放到了proxySelector上,在okhttp中默认的proxy是DefaultProxySelector

public List<Proxy> select(URI var1) {...}

跟踪到了这个方法,参数是URI 返回是List 这个方法的作用是通过uri来获得一个Proxy的集合,list中的第一个Proxy使用失败后会自动选择下一个,而默认的ProxySelecter中list中值提供一个Proxy。

我自己定义了一个ProxySelector后提供了n个Proxy就实现了“自定义重试连接次数”的目的了

public class MultiProxySelector extends DefaultProxySelector {

    int count;

    MultiProxySelector(int count){
        this.count = count;
    }

    @Override
    public List<Proxy> select(URI uri) {
        List<Proxy> list = new ArrayList<>(count);
        List<Proxy> select = super.select(uri);
        for (int i=0;i<count;i++){
            list.addAll(select);
        }
        return list;
    }

}

在构建httpClient的时候设置成我自定义的ProxySelector

new OkHttpClient().newBuilder().proxySelector(new MultiProxySelector(retryTimes))
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值