cmd*_*cmd 14 java rest multithreading jax-rs jersey
我有一个用JAX-RS实现的REST服务.有些操作需要很长时间才能完成,可能需要15-30分钟.对于这些情况,我倾向于派遣后台线程来处理长时间运行的操作,然后立即响应HTTP状态202 ACCEPTED.响应将包含一个带有URL的位置标头,客户端可以使用该标头来轮询进度.
这种方法需要创建线程来处理长时间运行的操作,这样就可以立即返回202 ACCEPTED.我也知道在Java EE容器中创建自己的线程通常是不好的做法!
我的问题如下:
另外,为了避免管理我自己的线程,我查看了JAX-RS异步服务器api.不幸的是,虽然这提高了服务器吞吐量,但它不允许我立即响应ACCEPTED.
泽西州声明如下:
Note that the use of server-side asynchronous processing model will not improve the
request processing time perceived by the client. It will however increase the
throughput of the server, by releasing the initial request processing thread back to
the I/O container while the request may still be waiting in a queue for processing or
the processing may still be running on another dedicated thread. The released I/O
container thread can be used to accept and process new incoming request connections.
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏.谢谢!
我也知道在 Java EE 容器中创建自己的线程通常是不好的做法!
尽管上述情况在大多数情况下是正确的,但在这种情况下您别无选择。至少不要Thread自己创建实例。让一个ExecutorService为你做。如果有的话,让它ExecutorService有一个足够大的池并与您的所有组件共享。
我认为Jersey Async 文档很好地阐述了这个主题。这是一个简短的片段:
@Path("/async/longRunning")
public class MyResource {
@GET
public void longRunningOp(@Suspended final AsyncResponse ar) {
executor.submit(
new Runnable() {
public void run() {
executeLongRunningOp();
ar.resume("Hello async world!");
} });
}
}
Run Code Online (Sandbox Code Playgroud)
当涉及到文档中的以下引用时:
请注意,使用服务器端异步处理模型不会改善客户端感知的请求处理时间。(...)
我觉得你有点误解了。文档的作者在这里试图表达的是,异步处理本身并不能加快速度。但可以使用以下命令立即返回响应:
return Response.status(Status.ACCEPTED).build();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7831 次 |
| 最近记录: |