提问者:小点点

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


如何在泽西客户端2中使用自定义配置的Apache HttpClient?

带缓存的HttpClient(来自apache文档)

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;
    }

但是如何使用自定义超文本传输协议客户端配置,如上所述?


共1个答案

匿名用户

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

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

参见示例。

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