背景
項目中使用OkHttp訪問三方服務
參數
創建okhttp客戶端類的時候需要設置一些參數,有些可能是坑,僅供參考:
client = new OkHttpClient.Builder() .dispatcher(new Dispatcher(executorService)) .connectionPool(new ConnectionPool(maxIdleConnections, keepAliveDurationMills, TimeUnit.MILLISECONDS)) .readTimeout(readTimeoutMills, TimeUnit.MILLISECONDS) .connectTimeout(connectTimeoutMills, TimeUnit.MILLISECONDS) .writeTimeout(writeTimeoutMills, TimeUnit.MILLISECONDS) .protocols(Util.immutableList(Protocol.HTTP_1_1)) .connectionSpecs(Arrays.asList(TLS_SPEC, ConnectionSpec.CLEARTEXT)) .build(); client.dispatcher().setMaxRequests(maxRequests); client.dispatcher().setMaxRequestsPerHost(maxRequestsPerHost); |
||
參數 |
意義 |
推薦值及原則 |
executorService |
內部執行http請求的實際線程池 |
默認executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false)); 沒有常駐線程,性能低,線程沒有限制上限。 |
maxIdleConnections |
連接池大小,指單個okhttpclient實例所有連接的連接池。 |
默認:5,值的設置與業務請求量有關,如果請求三方的tps是200,建議這個值設置在200左右。 |
keepAliveDurationMills |
連接池中連接的最大時長 |
默認5分鍾,依據業務場景來確定有效時間,如果不確定,那就保持5分鍾 |
connectTimeoutMills |
連接的最大超時時間 |
默認10秒 |
readTimeoutMills |
讀超時 |
默認10秒,如果是流式讀,那建議設置長一點時間。 With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. |
writeTimeoutMills |
寫超時 |
默認10秒,如果是流式寫,那建議設置長一點時間 |
maxRequests |
當前okhttpclient實例最大的並發請求數 |
默認:64,默認的64一般滿足不了業務需要。這個值一般要大於maxRequestPerHost,如果這個值小於maxRequestPerHost會導致,請求單個主機的並發不可能超過maxRequest. |
maxRequestPerHost |
單個主機最大請求並發數,這里的主機指被請求方主機,一般可以理解對調用方有限流作用。注意:websocket請求不受這個限制。 |
默認:4,一般建議與maxRequest保持一致。 這個值設置,有如下幾個場景考慮: (1)如果被調用方的並發能力只能支持200,那這個值最好不要超過200,否則對調用方有壓力; (2)如果當前okhttpclient實例只對一個調用方發起調用,那這個值與maxRequests保持一致; (3)如果當前okhttpclient實例在一個事務中對n個調用方發起調用,n * maxReuestPerHost要接近maxRequest |
maxRequests和maxReuestsPerHost值的設置與executorService線程池的設置有關聯,請注意。maxRequests和maxRequestPerHost是okhttp內部維持的請求隊列,而executorservice是實際發送請求的線程。如果maxRequests和maxReuestPerHost設置太大,executorService會因為線程太少而阻塞發送。