使用Jersey客户端重置连接

我在生产中看到很多连接重置。可能有多种原因,但我想确保代码中没有连接泄漏。我在代码中使用Jersey客户端

Client this.client = ApacheHttpClient.create(); client.resource("/stores/"+storeId).type(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class,indexableStore); 

最初我用以下方式实例化客户端客户端this.client = Client.create(),我们将其更改为ApacheHttpClient.create()。 我没有在响应上调用close()但我假设ApacheHttpClient会在内部执行,因为HttpClient executeMethod被调用,它会为我们处理所有的样板。 编写代码的方式是否存在潜在的连接泄漏?

就像你说的, Connection Reset可能是由许多可能的原因造成的。 一种可能是服务器在处理请求时超时,这就是客户端接收连接重置的原因。 这里回答问题的评论部分详细讨论了连接重置的可能原因。 我能想到的一个可能的解决方案是配置HttpClient以在发生故障时重试请求。 您可以像下面那样设置HttpMethodRetryHandler ( 参考 )。 您可能需要根据收到的exception修改代码。

 HttpMethodRetryHandler retryHandler = new HttpMethodRetryHandler() { public boolean retryMethod( final HttpMethod method, final IOException exception, int executionCount) { if (executionCount >= 5) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (!method.isRequestSent()) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent return true; } // otherwise do not retry return false; } }; ApacheHttpClient client = ApacheHttpClient.create(); HttpClient hc = client.getClientHandler().getHttpClient(); hc.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler); client.resource("/stores/"+storeId).type(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class,indexableStore);