1. 程式人生 > >非同步呼叫Webservice

非同步呼叫Webservice

非同步,說到非同步需要首先將以下同步。同步就是程式碼按照順序執行,當前面的程式碼的請求沒有正常返回結果的情況下,後面的程式碼是不能執行。而非同步正好和這點不同,非同步是程式碼執行後,不管當前的請求是否返回結果,後面的程式碼都會繼續執行。

1.   編寫服務端程式碼:

  1. publicclass AsynchronousService {  
  2.     public String execute() {  
  3.         System.out.println("正在執行此程式碼……");  
  4.         // 延遲5秒後,返回結果
  5.         try {  
  6.             Thread.sleep(5000
    );  
  7.         } catch (InterruptedException e) {  
  8.             e.printStackTrace();  
  9.         }  
  10.         return"完成";  
  11.     }  
  12. }  

2.   編寫services.xml程式碼,打包併發布至對應資料夾下

  1. <servicename="AsyncService">
  2.     <description>
  3.         AsyncService  
  4.     </description>
  5.     <parametername
    ="ServiceClass">
  6.         server.asynchronous.AsynchronousService  
  7.     </parameter>
  8.     <messageReceivers>
  9.         <messageReceivermep="http://www.w3.org/2004/08/wsdl/in-out"
  10.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
  11.         <messageReceivermep="http://www.w3.org/2004/08/wsdl/in-only"
  12.             class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
  13.     </messageReceivers>
  14. </service>

3.   客戶端程式碼:

  1. package client;  
  2. import java.io.IOException;  
  3. import javax.xml.namespace.QName;  
  4. import org.apache.axis2.addressing.EndpointReference;  
  5. import org.apache.axis2.client.Options;  
  6. import org.apache.axis2.client.async.AxisCallback;  
  7. import org.apache.axis2.context.MessageContext;  
  8. import org.apache.axis2.rpc.client.RPCServiceClient;  
  9. publicclass AsynTest {  
  10.     publicstaticvoid main(String[] args) throws IOException {  
  11.         String target = "http://localhost:8080/axis2/services/AsyncService";  
  12.         RPCServiceClient client = new RPCServiceClient();  
  13.         Options options = client.getOptions();  
  14.         options.setManageSession(true);  
  15.         EndpointReference epr = new EndpointReference(target);  
  16.         options.setTo(epr);  
  17.         QName qname = new QName("http://asynchronous.server""execute");  
  18.         //指定呼叫的方法和傳遞引數資料,及設定返回值的型別
  19.         client.invokeNonBlocking(qname, new Object[] {}, new AxisCallback() {  
  20.             publicvoid onMessage(MessageContext ctx) {  
  21.                 System.out.println(ctx.getEnvelope());  
  22.                 System.out.println("Message:" + ctx.getEnvelope().getFirstElement().getFirstElement().getFirstElement().getText());  
  23.             }  
  24.             publicvoid onFault(MessageContext ctx) {  
  25.             }  
  26.             publicvoid onError(Exception ex) {  
  27.             }  
  28.             publicvoid onComplete() {  
  29.             }  
  30.         });  
  31.         //斷點此處,檢視非同步結果
  32.         System.out.println("非同步WebService");  
  33.         //阻止程式退出
  34.         System.in.read();  
  35.     }  
  36. }