AsyncRestTemplate ListenableFuture <t>回调+超时

时间:2015-08-18 13:18:07

标签: java spring asynchronous

我已经配置了像这样的AsyncRestTemplate,这里只是一个例子来说明我正在使用 HttpComponentsAsyncClientHttpRequestFactory connectTimeout readTimeout 被初始化使用值 - 使用Spring 4.0.8 RELEASE:

    <bean id="myAsynchRequestFactory" class="org.springframework.http.client.HttpComponentsAsyncClientHttpRequestFactory">
        <property name="httpAsyncClient" ref="myCloseableHttpAsynchClient"></property>
        <property name="connectTimeout" value="444"></property>
        <property name="readTimeout" value="555"></property>
    </bean>

    <bean id="myAsynchRestTemplate" class="org.springframework.web.client.AsyncRestTemplate">
        <constructor-arg>
            <ref bean="myAsynchRequestFactory"/>
        </constructor-arg>
    </bean>

我还配置了一个 RequestConfig ,因为spring代码表明前一个方法已被弃用,所以我这样添加了它:

<bean id="myRequestConfigBuilder" class="org.apache.http.client.config.RequestConfig" factory-method="custom">
    <property name="connectionRequestTimeout" value="555"></property>
    <property name="connectTimeout" value="400"></property>
    <property name="socketTimeout" value="555"></property>
</bean>

<bean id="myRequestConfig" factory-bean="myRequestConfigBuilder" factory-method="build">
</bean>

<bean id="myHttpAsyncClientBuilder" class="org.apache.http.impl.nio.client.HttpAsyncClientBuilder">
    <property name="connectionManager" ref="myHttpAsyncConnectionManager"></property>
    <property name="defaultRequestConfig" ref="myRequestConfig"></property>
</bean>

<bean id="myHttpAsyncClientBuilder" class="org.apache.http.impl.nio.client.HttpAsyncClientBuilder">
    <property name="connectionManager" ref="myHttpAsyncConnectionManager"></property>
    <property name="defaultRequestConfig" ref="myRequestConfig"></property>
</bean>
<bean id="myCloseableHttpAsynchClient" factory-bean="myHttpAsyncClientBuilder" factory-method="build">
</bean>

现在我正在使用AsyncRestTemplate和它的 addCallback()方法(如图所示):

  response = myAsynchRestTemplate.getForEntity( ... );
  response.addCallback(new org.springframework.util.concurrent.ListenableFutureCallback<ResponseEntity<?>>() {

                    @Override
                    public void onSuccess(ResponseEntity<?> result) {
                        System.out.println("SUCCESS");
                    }

                    @Override
                    public void onFailure(Throwable ex) {
                        System.out.println("FAILURE")
                    }
                }

我希望当服务需要超过555ms才能回复时,永远不会调用onSuccess(...)。但这不会发生。即使我的服务假装延迟让我们说5000毫秒,无论如何都会调用onSuccess方法。

我在网上搜索了可能的解决方案,为回调添加了某种超时,但没有找到任何合适的。我尝试从4.0以来的任何版本中读取org.springframework.util.concurrent。*代码,但是还没有找到任何会阻止注册回调执行的内容。

我已经看过以下Stackoverflow问题:

How to cancel AsyncRestTemplate HTTP request if they are taking too much time?这个建议超时应该有效

ListenableFuture, FutureCallback and timeouts这个使用了一些Google Guava示例,但我使用的是org.springframework.util.concurrent.ListenableFuture

有没有人能解决这个问题呢?

更新

我找到了为什么这不起作用的根本原因......

HttpComponentsAsyncClientHttpRequestFactory 不接受我提供的RequestConfig。相反,它始终为null,并且将此类重新创建为RequestConfig.DEFAULT。这发生在这里:

来自HttpComponentesAsyncClientHttpRequestFactory:

@Override
public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
    HttpAsyncClient asyncClient = getHttpAsyncClient();
    startAsyncClient();
    HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
    postProcessHttpRequest(httpRequest);



    /** HERE: It tries to create a HttpContext **/
    HttpContext context = createHttpContext(httpMethod, uri);




    if (context == null) {
        context = HttpClientContext.create();
    }
    // Request configuration not set in the context
    if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
        // Use request configuration given by the user, when available
        RequestConfig config = null;
        if (httpRequest instanceof Configurable) {
            config = ((Configurable) httpRequest).getConfig();
        }
        if (config == null) {
            config = RequestConfig.DEFAULT;
        }
        context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
    }
    return new HttpComponentsAsyncClientHttpRequest(asyncClient, httpRequest, context);
}

但是方法createHttpContext(httpMethod,uri)总是返回null:

/**
 * Template methods that creates a {@link HttpContext} for the given HTTP method and URI.
 * <p>The default implementation returns {@code null}.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the http context
 */
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
    return null;
}

因此,重新创建了HttpContext并附加了 RequestConfig.DEFAULT

现在比较与非Asynch 版本, HttpComponentsClientHttpRequestFactory 这个重新创建一个带有超时的RequestConfig:

@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
    CloseableHttpClient client = (CloseableHttpClient) getHttpClient();
    Assert.state(client != null, "Synchronous execution requires an HttpClient to be set");
    HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
    postProcessHttpRequest(httpRequest);
    HttpContext context = createHttpContext(httpMethod, uri);
    if (context == null) {
        context = HttpClientContext.create();
    }
    // Request configuration not set in the context
    if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
        // Use request configuration given by the user, when available
        RequestConfig config = null;
        if (httpRequest instanceof Configurable) {
            config = ((Configurable) httpRequest).getConfig();
        }
        if (config == null) {




            /** LOOK HERE - THE SYNC WORLD HAS THIS WORKAROUND */
            if (this.socketTimeout > 0 || this.connectTimeout > 0) {
                config = RequestConfig.custom()
                        .setConnectTimeout(this.connectTimeout)
                        .setSocketTimeout(this.socketTimeout)
                        .build();
            }



            else {
                config = RequestConfig.DEFAULT;
            }
        }
        context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
    }
    if (this.bufferRequestBody) {
        return new HttpComponentsClientHttpRequest(client, httpRequest, context);
    }
    else {
        return new HttpComponentsStreamingClientHttpRequest(client, httpRequest, context);
    }
}

当我使用 SimpleClientHttpRequestFactory 而不是我配置的超时而不是 onSuccess(...)时, onFailure(...)使用 SocketTimeoutException

调用方法

这完全令人费解 - 也许任何人都可以提示为什么HttpComponentsAsyncClientHttpRequestFactory按原样实现?

是否有正确使用RequestConfig对象的示例?

1 个答案:

答案 0 :(得分:1)

中讨论了这个问题

https://jira.spring.io/browse/SPR-12540

Spring 4.3中有一个解决方案(当前Spring为4.2),时间的解决方案是将HttpComponentsAsyncClientHttpRequestFactory和@Override子类化为getHttpContext方法。