正确处理运动衫中的后台通话 [英] Correct handling of background calls in jersey
问题描述
我必须对Web应用程序中的Web服务进行一些后台调用.通话的响应时间并不是很紧迫,对我而言几乎没有任何意义.它仅在极少数情况下会发生变化,在这种情况下,我将通过引发异常或记录故障或其他内容对此做出反应.现在,我要问的一个问题是在Jersey Client 2中正确处理此类紧急呼叫.
I have to do some background calls to a web service within a web application. The response of the call is not really time-critical and barely interesting for me. It changes only in rare cases, where I will react to it by throwing a exception, or logging the failure or something. My conrete question now refers to the correct handling of such asynch calls in Jersey Client 2.
选项1使用来自jersey的异步调用,但随后为每个响应启动一个线程.选项2立即启动一个线程,并从该线程内部使用jersey.
Option 1 uses the async calls from jersey, but then starts a thread for each response. Option 2 would immediatly start a thread and use jersey from inside this thread.
通常哪种方法更可取?
选项1
private static final ExecutorService executorService = Executors.newFixedThreadPool(20);
-
Client client = ClientBuilder.newClient();
WebTarget target = client.target("somehost").path("somepath");
final AsyncInvoker asyncInvoker = target.request().async();
final Future<Response> responseFuture = asyncInvoker.post(Entity.json(myjsonobject));
executorService.execute(new Worker(responseFuture));
-工作者线程
public class Worker implements Runnable {
private Future<Response> futureResponse;
public Worker(Future<Response> futureResponse){
this.futureResponse = futureResponse;
}
@Override
public void run() {
try {
final Response response = futureResponse.get();
if(response.getStatus() == 500)
doSomething();
} catch(Exception e) {
e.printStackTrace();
}
}
}
选项2
private static final ExecutorService executorService = Executors.newFixedThreadPool(20);
-
executorService.execute(new Worker());
-工作者线程
public class Worker implements Runnable {
public Worker(){
}
@Override
public void run() {
try {
Client client = ClientBuilder.newClient();
WebTarget target = client.target("somehost").path("somepath");
ClientResponse response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.json(myjsonobject), ClientResponse.class);
if(response.getStatus() == 500) {
doSomething();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
推荐答案
(而不是尝试实现非阻塞" Future.get()
(使用另一个线程),您可以简单地使使用 InvocationCallback
,将实例传递给 get
方法.例如
Instead of trying to implement a "non-blocking" Future.get()
(with another thread), you can simply make use of the InvocationCallback
, passing an instance to the get
method. For example
Future<Response> future = target.request().async().get(new InvocationCallback<Response>(){
@Override
public void completed(Response response) {
System.out.println(response.readEntity(String.class));
response.close();
client.close();
}
@Override
public void failed(Throwable throwable) { /** Log exception **/ }
});
请参见异步客户端回调
这篇关于正确处理运动衫中的后台通话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!