使用Pooling实现Spring RestTemplate

时间:2017-01-25 08:16:47

标签: spring performance httpclient resttemplate

在我的Spring应用程序中,我对部署在我的应用程序所在的同一服务器上部署的服务进行了大量的休息调用, 我们曾经在需要调用Web服务时创建一个新的RestTemplate(),我知道这是不高效的,因为每次调用都会创建并销毁一个新的http连接,因此我编写了以下配置调用和@Autowired a restTempalte在我需要调用web服务的每个类“@service”中,我只需要知道我的方法是否正确。

@Configuration
public class HttpConfig {
private static final Logger logger =     LoggerFactory.getLogger(HttpConfig.class);
@Value(value="${MAX_TOTAL_CONNECTIONS}")
public String MAX_TOTAL_CONNECTIONS;

@Value(value="${MAX_CONNECTIONS_PER_ROUTE}")
public String MAX_CONNECTIONS_PER_ROUTE;

@Value(value="${CONNECTION_TIMEOUT_MILLISECONDS}")
public String CONNECTION_TIMEOUT_MILLISECONDS;


@Bean
public ClientHttpRequestFactory httpRequestFactory() {
    return new HttpComponentsClientHttpRequestFactory(httpClient());
}

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
    List<HttpMessageConverter<?>> converters = restTemplate
            .getMessageConverters();

           for (HttpMessageConverter<?> converter : converters) {
           if (converter instanceof MappingJackson2HttpMessageConverter) {
            MappingJackson2HttpMessageConverter jsonConverter = (MappingJackson2HttpMessageConverter) converter;
            jsonConverter.setObjectMapper(new ObjectMapper());
           }
          }

    logger.debug("restTemplate object cretaed====================================");
    return restTemplate;
 }

@Bean
public HttpClient httpClient() {
    HttpClient httpClient =null;
    try {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        // disable SSL check
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws CertificateException {
                return true;
            }
        }).build();
        httpClientBuilder.setSslcontext( sslContext);
        // don't check Hostnames
        HostnameVerifier hostnameVerifier =NoopHostnameVerifier.INSTANCE;
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();

        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
        connMgr.setMaxTotal(Integer.parseInt(MAX_TOTAL_CONNECTIONS));
        connMgr.setDefaultMaxPerRoute(Integer.parseInt(MAX_CONNECTIONS_PER_ROUTE));
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(Integer.parseInt(CONNECTION_TIMEOUT_MILLISECONDS)).build();

        httpClientBuilder.setDefaultRequestConfig(config);          
        httpClientBuilder.setConnectionManager( connMgr);

        // to avoid nohttpresponse
        httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (exception instanceof org.apache.http.NoHttpResponseException) {
                        return true;
                }
                return false;
            }
        });
        httpClient = httpClientBuilder.build();
    }catch (Exception e) {
        logger.error("Excption creating HttpClient: " ,e);
    }
    return httpClient;
}

}

0 个答案:

没有答案