异步处理

可以使用 JAX-RS 2.0 中的异步处理技术来处理线程。异步处理在客户机 API 和服务器 API 中均受支持。有关客户机 API 和服务器 API 中的异步处理的更多信息,请参阅 JSR 339:JAX-RS 2.0: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");		    
    	         }
    }
WebSphere® Application Server(传统) 中的 JAX-RS 2.0 实现支持 EJB 以及将无状态和单独会话 bean 用作根资源类。使用 @Asynchronous 对 EJB 方法进行注释时,EJB 容器会自动为其执行分配必需资源。因此,在此场景中,不需要使用执行程序也可生成异步响应。例如,
@Stateless
@Path("/")
class EJBResource {

	@GET @Asynchronous
	public void longRunningOp(@Suspended AsyncResponse ar) {
		executeLongRunningOp();
		ar.resume("Hello async world!");
	}
}
在此情况下,不需要执行显式线程管理,因为这由 EJB 容器控制。通过针对注入的 AsyncResponse 调用 resume 生成响应。因此,longRunningOp 的返回类型为 void。

指示主题类型的图标 参考主题



时间戳记图标 最近一次更新时间: last_date
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=rwbs_jaxrs2
文件名:rwbs_jaxrs2.0_async.html