使用启用缓存的 Apache HttpClient 作为 Jersey 2 客户端

Use Apache HttpClient with caching enabled as Jersey 2 client

如何将自定义配置的 Apache HttpClient 与 Jersey Client 2 一起使用?

带缓存的 HttpClient (from apache docs)

CacheConfig cacheConfig = CacheConfig.custom()
        .setMaxCacheEntries(1000)
        .setMaxObjectSize(8192)
        .build();
RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(30000)
        .setSocketTimeout(30000)
        .build();
CloseableHttpClient cachingClient = CachingHttpClients.custom()
        .setCacheConfig(cacheConfig)
        .setDefaultRequestConfig(requestConfig)
        .build();

一般情况下使用 Apache Http 可以通过设置

protected ClientConfig getClientConfig() {
        ClientConfig config = new ClientConfig();
        config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);

        final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

        config.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);

        final ApacheConnectorProvider connector = new ApacheConnectorProvider();
        config.connectorProvider(connector);

        return config;
    }

但是如何像上面那样使用自定义的 http 客户端配置?

您可以使用 ApacheHttpClientBuilderConfigurator。所以你可以这样做:

config.register(new ApacheHttpClientBuilderConfigurator() {
   public HttpClientBuilder configure(HttpClientBuilder httpClientBuilder) {
      return httpClientBuilder.setDefaultRequestConfig(requestConfig);
   }
});

参见the example

目前没有正确支持 Apache 缓存客户端。您可以从方法中 return CachingHttpClientBuilder,但是 HttpClientBuilder 没有 getter 来查看已经设置的内容,因此您需要从头开始设置所有内容。