非同步處理

您可以使用 JAX-RS 2.0 中的非同步處理技術,來處理執行緒。Client API 和 Server API 中都支援非同步處理。如需 Client API 和 Server API 中非同步處理的相關資訊,請參閱 JSR 339: JAX-RS 2.0: The Java API for RESTful Web Services 的第 8 章 "Specification"。

下列兩個範例顯示 Client API 和 Server API 中的非同步處理:
  • Client 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 
               } 
    }); 
  • Server 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,以及支援使用 Stateless Session 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 傳回類型是 void。

指示主題類型的圖示 參照主題



「時間戳記」圖示 前次更新: 2016 年 11 月 30 日
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=rwlp_jaxrs2.0_asyn
檔名:rwlp_jaxrs2.0_asyn.html