use*_*775 1 java spring httpclient keep-alive
我有一个 Java/Spring 项目,其中使用 Oauth2RestTemplate 并使其使用 HttpClient (org.apache.http.client.Httpclient) 而不是默认的 SimpleClient
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
oAuth2RestTemplate.setRequestFactory(requestFactory);
Run Code Online (Sandbox Code Playgroud)
对此,我想知道/理解是否始终为所有请求发送保持活动标头?
如果总是发送,有办法禁止发送吗?我看到一篇文章 -在 Apache HttpClient 中禁用 Keep Alive,其中讨论了禁用它,但它建议对 httpMethod 进行设置。我不确定如何在上面描述的代码设置中访问此 httpMethod。
使用仅返回 false 的方法ConnectionReuseStrategy来实现 a 。keepAlive()见于.setConnectionReuseStrategy()HttpClientBuilder
您可能还想发送一个Connection值为 的标头close。
例子:
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader(HttpHeaders.CONNECTION, "close"));
HttpClientBuilder builder = HttpClients.custom().setDefaultHeaders(headers)
.setConnectionReuseStrategy(
new ConnectionReuseStrategy() {
@Override
public boolean keepAlive(HttpResponse httpResponse, HttpContext httpContext) {
log.info("**** keepAlive strategy returning false");
return false;
}
});
CloseableHttpClient httpClient = builder.build();
HttpGet httpGet = new HttpGet("https://google.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
log.info("Response status: " + response.getStatusLine());
response.close();
Run Code Online (Sandbox Code Playgroud)
一些附加信息:
1. Keep-Alive 头
当大多数人说keep-aliveheader 时,他们通常指的是一个不同的 header,称为Connection. 这两个标头一起工作:
HTTP/1.1 200 OK
...
Connection: Keep-Alive
Keep-Alive: timeout=5, max=1000
...
Run Code Online (Sandbox Code Playgroud)
标Connection头暗示应重新使用连接。标Keep-Alive头指定连接应保持打开状态的最短时间,以及连接可重复使用的最大请求数。
Connection标头的常见值为keep-alive和close。服务器和客户端都可以发送此标头。如果Connection标头设置为close,则Keep-Alive标头将被忽略。
2.HTTP/1.1和HTTP/2
对于 HTTP/1.1,默认情况下连接是持久的。该Keep-Alive标头已被弃用(HTTP 规范中不再定义),尽管许多服务器仍然发送它们以实现向后兼容性。
无法处理 HTTP/1.1 持久连接的客户端应设置一个Connection值为 的标头close。
HTTP/2 使用多路复用;Connection和header都不Keep-Alive应该与 HTTP/2 一起使用。
3. 代理和缓存的作用
一般来说,持久连接不能通过非透明代理工作。他们会默默地删除任何Connection或Keep-Alive标头。
4. 连接处理
由于持久连接现在是 HTTP/1.1 的默认设置,因此我们需要一种机制来控制何时/如何使用它们。对于 Apache http 客户端,ConnectionReuseStrategy确定连接是否应该持久,同时ConnectionKeepAliveStrategy指定连接可重用的最大空闲时间。
| 归档时间: |
|
| 查看次数: |
7066 次 |
| 最近记录: |