我编写了简单的REST Web服务客户端类,它使用JAX-RS 2.0客户端API来发出REST请求。我试图弄清楚如何为每次调用设置请求超时。以下是请求的代码:
Client client = ClientBuilder.newBuilder().build();
WebTarget resourceTarget = client.target(restServiceUrl)
.path("{regsysID}/{appointmentID}/")
.resolveTemplate("regsysID", regSysId)
.resolveTemplate("appointmentID", apptId);
Invocation invocation = resourceTarget.request(MediaType.APPLICATION_JSON).buildPut(null);
String createSessionJson = invocation.invoke(String.class);
您可以通过首先创建ClientConfig并在创建新客户端时将其作为参数提供来完成此操作。
import org.glassfish.jersey.client.ClientProperties;
ClientConfig configuration = new ClientConfig();
configuration.property(ClientProperties.CONNECT_TIMEOUT, 1000);
configuration.property(ClientProperties.READ_TIMEOUT, 1000);
Client client = ClientBuilder.newClient(configuration);
注意:这是JAX-RS 2.1上提供的新方法
这是一个非常古老的帖子,但下面的代码将适用于球衣和resteasy。
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
clientBuilder.readTimeout(12, TimeUnit.SECONDS);
Client client = clientBuilder.build();
使用Resteasy,可以通过构建您的客户端来实现。
Client client = new ResteasyClientBuilder()
.establishConnectionTimeout(2, TimeUnit.SECONDS)
.socketTimeout(2, TimeUnit.SECONDS)
.build();
我还没有看到你可以通过ClientBuilder.newClient(Configuration configuration)
设置的标准配置属性列表,这些属性是使这个便携式所需的。
首先,您必须添加相关的依赖项(这里是WildFly 10.1):
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.14.Final</version>
<scope>provided</scope>
</dependency>
接下来 - 创建一个普通的Apache HttpClient并使用覆盖一个方法将其推送到RestEasy Engine,这会导致问题:
// create here a normal Apache HttpClient with all parameters, that you need
HttpClient httpClient = createHttpClient(connectTimeout,
socketTimeout,
connectionRequestTimeout,
maxTotalHTTPConnections);
// Deprecated Apache classes cleanup https://issues.jboss.org/browse/RESTEASY-1357
// Client Framework not honoring connection timeouts Apache Client 4.3 https://issues.jboss.org/browse/RESTEASY-975
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient) {
@Override
protected void loadHttpMethod(ClientInvocation request, HttpRequestBase httpMethod) throws Exception {
super.loadHttpMethod(request, httpMethod);
httpMethod.setParams(new BasicHttpParams());
}
};
return new ResteasyClientBuilder().httpEngine(engine).build();
看看https://issues.jboss.org/browse/RESTEASY-975似乎,问题刚刚在3.1.0.Final版本中得到解决。
对于使用较旧的JAX-RS 2.0 API和旧的Resteasy实现的人,您可以使用以下方法:
Client client = new ResteasyClientBuilder()
.establishConnectionTimeout(3, TimeUnit.SECONDS)
.socketTimeout(5, TimeUnit.SECONDS).build();
尽管名称,socketTimeout代表“读取超时”,因为由文档,它代表“等待数据的超时”。
如果您正在使用Jersey 2.x这是一个简单的解决方案,它对我有用
import com.jclient.JClient;
Client c = Client.create();
WebResource webResource = c.resource("requestUrl");
c.setConnectTimeout(yourMins*60*1000);