首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsyncRestTemplate ListenableFuture<T>回调+超时

AsyncRestTemplate ListenableFuture<T>回调+超时
EN

Stack Overflow用户
提问于 2015-08-18 13:18:07
回答 1查看 3.3K关注 0票数 2

我配置了一个像这样的AsyncRestTemplate,这里只是一个例子,说明我使用的是一个HttpComponentsAsyncClientHttpRequestFactory,其中connectTimeout和readTimeout都是用值初始化的--使用Spring4.0.8发行版:

代码语言:javascript
复制
    <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代码建议不再推荐前一个方法,因此我按如下方式添加了它:

代码语言:javascript
复制
<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()方法(如图所示):

代码语言:javascript
复制
  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")
                    }
                }

我希望onSuccess(.)当服务超过555 is才能回复时,将不会调用。但这是不可能的。即使我的服务假装延迟了5000 my,无论如何也会调用onSuccess方法。

我在网上搜索了一些可能的解决方案,以便在回调中添加某种超时,但没有找到合适的解决方案。我试着在自4.0以来的任何版本中阅读org.Spring Frawork.util.Concurr.*代码,但是还没有找到任何可以阻止注册回调执行的内容。

我已经看到了以下Stackoverflow问题:

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

这一个是使用Google的例子,但我使用的是org.springframework.util.concurrent.ListenableFuture

有谁能解决这个问题吗?

更新

我找到了这不起作用的根本原因..。

HttpComponentsAsyncClientHttpRequestFactory不接受我提供的RequestConfig。相反,它总是空的,并且被重新创建为RequestConfig.DEFAULT。

来自HttpComponentesAsyncClientHttpRequestFactory:

代码语言:javascript
复制
@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:

代码语言:javascript
复制
/**
 * 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;
}

这样,就可以重新创建RequestConfig.DEFAULT并获得附加的HttpContext。

现在,HttpComponentsClientHttpRequestFactory. 这个与非同步的版本进行比较。这一次使用超时重新创建RequestConfig:

代码语言:javascript
复制
@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对象的示例?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-18 16:18:00

这个问题将在

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

在Spring4.3中有一个解决方案(当前的Spring是4.2),此时的解决方案是子类HttpComponentsAsyncClientHttpRequestFactory和@重写getHttpContext方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32073596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档