无法在JBoss上的Resteasy Client上设置超时

时间:2016-02-08 14:09:52

标签: java rest java-ee resteasy jboss6.x

我正在尝试在JBoss EAP服务器上创建一个休息客户端,我需要确保超时会在连接卡住时终止。

我的代码如下所示:

int timeout = 5000;
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).setConnectTimeout(timeout).build();
HttpClientBuilder builder = HttpClientBuilder.create();
HttpClient httpClient = builder.setDefaultRequestConfig(defaultRequestConfig).build();
// Previous try
// HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

ClientExecutor executor = new ApacheHttpClient4Executor(httpClient);        

ClientRequest cr = new ClientRequest("http://www.someserviceurl.com/", executor);
JSONObject jData = new JSONObject();

jData.put("param1", param1);
jData.put("param2", param2);

cr.accept("application/json");
cr.body("application/json", jData.toString());

ClientResponse<String> cres = cr.post(String.class);

目前这段代码没有超时,但是永远陷入困境。我做错了什么?

2 个答案:

答案 0 :(得分:2)

Jboss支持部门的正式回答是使用配置构建器并应用它实现ApacheHttpClient4Executor类中的方法loadHttpMethod。以下是具有一些配置的客户端示例:

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ProxyFactory;
import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;

// ......

RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder.setConnectTimeout(100);
requestBuilder.setSocketTimeout(100);
requestBuilder.setConnectionRequestTimeout(100);
final RequestConfig config = requestBuilder.build();

HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultRequestConfig(config);

CloseableHttpClient client = httpClientBuilder.build();

ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(
        client) {
    @Override
    public void loadHttpMethod(ClientRequest request,
            HttpRequestBase httpMethod) throws Exception {
        httpMethod.setConfig(config);
        super.loadHttpMethod(request, httpMethod);
    }
};

// use it in your ClientRequest or Proxy interface
final FooService fooService = ProxyFactory.create(FooService.class, host, executor);

答案 1 :(得分:1)

显然这是RestEasy的已知问题,已在版本3.0.9.Final上修复。

您可以看到错误报告here

要解决此问题,请升级RestEasy或使用已弃用的DefaultHttpClient

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, timeout);
ClientExecutor executor = new ApacheHttpClient4Executor(httpClient);

ClientRequest cr = new ClientRequest("http://www.someserviceurl.com/", executor);