How to keep connection alive in Java 11 http client

二次信任 提交于 2019-11-28 05:26:56

问题


I'm using the Java 11 HttpClient with HTTP/2 and need to keep connection alive for few minutes, but the builder does not have the option to set it. Is there a way to specify this and make client keep the connection alive for some time?


回答1:


If you build a standard HttpClient e.g. using HttpClient.newHttpClient(); by default a connection pool is created. This pool keeps the connections alive by default for 1200 seconds (20 minutes).

If you want to change the keep-alive timeout you can do so using the property jdk.httpclient.keepalive.timeout. However the value is only read once when the class jdk.internal.net.http.ConnectionPool is loaded. Afterwards it can't be changed anymore.

Therefore you have to set this property for the whole JVM:

-Djdk.httpclient.keepalive.timeout=99999

Or at runtime before the ConnectionPool class has been loaded:

System.setProperty("jdk.httpclient.keepalive.timeout", "99999");

A third option is to using a file named ${java.home}/conf/net.properties and set the property in there.




回答2:


Both HTTP/2 and HTTP/1.1 connections are kept alive by default. There are some exceptions when several concurrent connections are opened to the same host - then only one of them will be kept alive.



来源:https://stackoverflow.com/questions/53617574/how-to-keep-connection-alive-in-java-11-http-client

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