java - AsyncRestTemplate ListenableFuture<T> 回调 + 超时

标签 java spring asynchronous

我已经像这样配置了一个 AsyncRestTemplate,这里只是一个例子来表明我正在使用 HttpComponentsAsyncClientHttpRequestFactory 并初始化 connectTimeoutreadTimeout带有值 - 使用 Spring 4.0.8 版本:

    <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")
                    }
                }

我希望当服务的回复时间超过 555 毫秒时永远不会调用 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

现在比较这个与非异步版本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 对象的示例?

最佳答案

这个问题在

中讨论

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

在Spring 4.3(目前的Spring是4.2)中有一个解决方案,暂时的解决方案是继承HttpComponentsAsyncClientHttpRequestFactory和@Override getHttpContext方法。

关于java - AsyncRestTemplate ListenableFuture<T> 回调 + 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32073596/

相关文章:

java - Spring Web MVC Post请求多个对象

javascript - 嵌套的异步循环推送到不调用主回调的异步队列

java - 未找到 Thymeleaf 静态图像

java - 使用 Activiti 创建原生查询

spring - 在 Spring Boot 中的 Yaml 中转义 Map 键中的点

c# - C#异步套接字不会返回整页

c# - 使用 async/await 进行设计——一切都应该是异步的吗?

java - 无法解析 android studio 中的符号 R

java - 我应该在我的 javadoc 类和方法注释中写什么?

java - JSF 组件渲染器