异步处理
可在 JAX-RS 2.0 中使用异步处理方法来处理线程。异步处理在客户机 API 和服务器 API 中都是受支持的。有关在客户机和服务器 API 中进行异步处理的更多信息,请参阅 JSR 339: JAX-RS 2.0: The Java API for RESTful Web Services(“规范”)的第 8 章。
以下两个示例显示客户机 API 和服务器 API 中的异步处理:
- 客户机 API 中的异步处理:
Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://example.org/customers/{id}"); target.resolveTemplate("id", 123).request().async().get( new InvocationCallbackCustomer() { @Override public void completed(Customer customer) { // Do something } @Override public void failed(Throwable throwable) { // Process error } });
- 服务器 API 中的异步处理:
@Path("/async") public class MyResource { @GET public void getAsync(@Suspended final AsyncResponse asyncResponse){ CompletionCallback callBack = new CompletionCallback(){ @Override public void onComplete(Throwable throwable) { ... } }; asyncResponse.register(callBack); asyncResponse.resume("some Response"); } }
Liberty 中的 JAX-RS 2.0 实现支持 EJB,并支持将无状态 bean 和单独会话 bean 用作根资源类。如果 EJB
方法是使用 @Asynchronous 注释的,那么 EJB 容器自动分配执行时所需的资源。因此,在此场景中,不必使用执行程序来生成异步响应。例如,
@Stateless
@Path("/")
class EJBResource {
@GET @Asynchronous
public void longRunningOp(@Suspended AsyncResponse ar) {
executeLongRunningOp();
ar.resume("Hello async world!");
}
}
在此情况下,不需要显式线程管理,因为它在 EJB 容器的控制之下。响应是在通过对已注入 AsyncResponse 调用复原而产生的。因此,longRunningOp 的返回类型为空。