Roh*_*hit 0 java rest web-services jax-rs
我有一个案例要在我的项目中实施。下面是一个必须实施的示例休息服务
@GET
@Path("/test/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String getData(@PathParam("id") String id) {
//Some processing to get value of String
String result = doSomeProcessing();
//I want to return this result to GUI and call one more rest api
// and end this process without waiting for response from second
//call
new Thread(){
//call second rest api
}.start();
return result;
}
Run Code Online (Sandbox Code Playgroud)
这是使用新线程调用第二个休息 API 并返回结果而不等待第二个休息 API 响应的好方法吗?我还研究了异步 Rest 调用,但它并不完全符合我的要求。请指教。提前致谢
避免Thread直接以s开头。考虑ExecutorService改为如下所示:
@Singleton
@Path("foo")
public class FooResource {
private ExecutorService executor;
@PostConstruct
public void onCreate() {
// Creates a thread pool that reuses a fixed number
// of threads operating off a shared unbounded queue
this.executor = Executors.newFixedThreadPool?(10);
}
@GET
public Response getFoo() {
String result = doSomeProcessing();
// Submits a Runnable task for execution
executor.submit(new LongRunningTask());
return Response.ok(result).build();
}
@PreDestroy
public void onDestroy() {
// Initiates an orderly shutdown in which previously submitted
// tasks are executed, but no new tasks will be accepted.
this.executor.shutdownNow();
}
}
Run Code Online (Sandbox Code Playgroud)
public class LongRunningTask implements Runnable {
@Override
public void run() {
try {
// Simulate a long running task
// Don't do it in a real application
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
探索ExecutorsAPI 以了解有关如何创建ExecutorService实例的详细信息。
在 Java SE 和 Servlet 容器中,您可以ExecutorService为长时间运行的任务使用 。在 Java EE 容器中,您应该使用 aManagedExecutorService代替:
@Resource
ManagedExecutorService executor;
Run Code Online (Sandbox Code Playgroud)
一旦它成为容器管理的资源,就不需要手动实例化和处置它。
| 归档时间: |
|
| 查看次数: |
6076 次 |
| 最近记录: |