OkHttpClient limit number of connections?

﹥>﹥吖頭↗ 提交于 2019-12-19 14:23:11

问题


Is it possible with OkHttpClient to limit the number of live connections? So if limit reached, no new connection is picked and established?

My app starts many connection at same time.


回答1:


The number of connections is configurable in the Dispatcher, not in the ConnectionPool that only allows to configure the max idle connections and the keep alive functionality.

The dispatcher allows to configure the number of connections by hosts and the max number of connections, defaults are 5 per hosts and 64 in total. This can seems low for HTTP/1 but are OK if you use HTTP/2 as multiple requests can be send to one connection.

To configure the dispatcher, follow these steps :

Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(100);
dispatcher.setMaxRequestsPerHost(10);
OkHttpClient client = new OkHttpClient.Builder()
    .dispatcher(dispatcher)
    .build();



回答2:


You could attempt to configure the maximum number of idle network connections by setting a ConnectionPool on your OkHttpClient.Builder.

int maxConnections = 5;
int keepAliveDuration = 15000;
ConnectionPool cp = new ConnectionPool(maxConnections, keepAliveDuration, TimeUnit.MILLISECONDS);

new OkHttpClient.Builder()
    .connectionPool(cp)
    .build();


来源:https://stackoverflow.com/questions/42299791/okhttpclient-limit-number-of-connections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!