okHttp3配置,易造成生产事故

321 阅读1分钟
private static final String PROXY_HOST = System.getenv().get("PROXY_HOST");
private static final String PROXY_PORT = System.getenv().get("PROXY_PORT");
protected static final OkHttpClient httpClient = getHttpClient();

private static OkHttpClient getHttpClient() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    Dispatcher dispatcher = new Dispatcher();
    //允许同时被执行的并发请求数量,默认为64,注意根据实际业务调整
    dispatcher.setMaxRequests(100);
    //相同host允许同时被执行的并发请求数量
    dispatcher.setMaxRequestsPerHost(50);
    builder.dispatcher(dispatcher);
    builder.retryOnConnectionFailure(true);
    // 连接数池大小,根据实际情况调整
    builder.connectionPool(new ConnectionPool(50, 120, TimeUnit.SECONDS));
    //日志拦截器
    if ("DEBUG".equalsIgnoreCase(LOG_LEVEL)) {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new Logger());
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.interceptors().add(httpLoggingInterceptor);
    }

    //网络代理
    if (StringUtils.isNotBlank(PROXY_HOST) && StringUtils.isNotBlank(PROXY_PORT)) {
        builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT))));
    }

    return builder.build();
}