Spring RestTemplate不允许持久的https连接

时间:2019-07-25 11:56:47

标签: spring-mvc ssl https resttemplate keep-alive

当通过https访问REST api时,我想使用Spring RestTemplate使用持久的http连接。我不能使它工作;将为每个请求创建一个新的连接,并且每次都会进行SSL握手。 是否可以使用RestTemplate通过https建立可重用的连接,如果可以,如何配置它?

我设置了RestTemplate来通过https发出请求。可以正常工作。 但是,我在日志中注意到,每个请求都会发生新的SSL握手。

我在测试中设置了RestTemplate,如下所示:

@Before
public void setupPersistentHttpConnectionBackedRestTemplate() {
    final SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
        sslContext,
        new String[] { "TLSv1.2" },
        null,
        SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
        .register("https", sslSocketFactory)
        .build();
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    final CloseableHttpClient httpClient = HttpClients.custom()
        .setSSLSocketFactory(sslSocketFactory)
        .setConnectionManager(connectionManager)
        .build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    restTemplate.getRestTemplate().setRequestFactory(requestFactory);
}

然后我像这样使用RestTemplate打几个电话:

ResponseEntity<String> response = restTemplate.exchange("/tomcat/sleep?millis={millis}", HttpMethod.GET, HttpEntity.EMPTY, String.class, SLEEP_DURATION);

我研究了spring-mvc和apache的代码,并注意以下内容。 在Spring RestTemplate execute方法中,创建一个新请求,然后执行该请求并返回结果。

            ClientHttpRequest request = createRequest(url, method);
            if (requestCallback != null) {
                requestCallback.doWithRequest(request);
            }
            response = request.execute();
            handleResponse(url, method, response);
            return (responseExtractor != null ? responseExtractor.extractData(response) : null);

依次结束于调用HttpComponentsClientHttpRequestFactory,每次都会在其中创建新的http上下文:


    @Override
    public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
        HttpClient client = getHttpClient();

        HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
        postProcessHttpRequest(httpRequest);
        HttpContext context = createHttpContext(httpMethod, uri);
        if (context == null) {
            context = HttpClientContext.create();
        }
...

在请求执行调用期间遵循调用链时,我最终遇到了Apache MainClientExec。在那里,它尝试根据路由和上下文用户令牌重用连接。执行请求后,将从上下文中检索用户令牌并存储以进行进一步查找。

    @Override
    public CloseableHttpResponse execute(
            final HttpRoute route,
            final HttpRequestWrapper request,
            final HttpClientContext context,
            final HttpExecutionAware execAware) throws IOException, HttpException {
...
        Object userToken = context.getUserToken();

        final ConnectionRequest connRequest = connManager.requestConnection(route, userToken);
...
            if (userToken == null) {
                userToken = userTokenHandler.getUserToken(context);
                context.setAttribute(HttpClientContext.USER_TOKEN, userToken);
            }
            if (userToken != null) {
                connHolder.setState(userToken);
            }
...

在使用https连接的情况下,将从SSL主体中检索用户令牌,然后从SSL证书中获取用户令牌:

    @Override
    public Object getUserToken(final HttpContext context) {
...
        if (userPrincipal == null) {
            final HttpConnection conn = clientContext.getConnection();
            if (conn.isOpen() && conn instanceof ManagedHttpClientConnection) {
                final SSLSession sslsession = ((ManagedHttpClientConnection) conn).getSSLSession();
                if (sslsession != null) {
                    userPrincipal = sslsession.getLocalPrincipal();
                }
            }
        }
    public Principal getLocalPrincipal() {
        if (this.cipherSuite.keyExchange != KeyExchange.K_KRB5 && this.cipherSuite.keyExchange != KeyExchange.K_KRB5_EXPORT) {
            return this.localCerts == null ? null : this.localCerts[0].getSubjectX500Principal();
        } else {
            return this.localPrincipal == null ? null : this.localPrincipal;
        }
    }

PoolingHttpClientConnectionManager尝试根据路由和状态(已存储用户令牌的状态)返回可重用的连接。

但是,由于RestTemplate每次都以具有新上下文的新请求开始,因此,uset令牌丢失,并且PoolingHttpClientConnectionManager无法找到可重用的连接,因此每次都创建一个新的连接。

我希望RestRemplate可以创建一个重用该连接的请求,而不是每次都创建一个新请求。

1 个答案:

答案 0 :(得分:0)

我试图实现相同的目标,而我看到的唯一方法是扩展HttpComponentsClientHttpRequestFactory来设置UserToken,在本例中为主体cert.getSubjectDN()然后覆盖createHttpContext(HttpMethod httpMethod,URI uri)

@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
    HttpClientContext context = HttpClientContext.create();
    context.setUserToken(userToken);
    return context;
}