非同步呼叫Webservice
阿新 • • 發佈:2019-01-23
非同步,說到非同步需要首先將以下同步。同步就是程式碼按照順序執行,當前面的程式碼的請求沒有正常返回結果的情況下,後面的程式碼是不能執行。而非同步正好和這點不同,非同步是程式碼執行後,不管當前的請求是否返回結果,後面的程式碼都會繼續執行。
1. 編寫服務端程式碼:
- publicclass AsynchronousService {
- public String execute() {
- System.out.println("正在執行此程式碼……");
- // 延遲5秒後,返回結果
- try {
-
Thread.sleep(5000
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return"完成";
- }
- }
2. 編寫services.xml程式碼,打包併發布至對應資料夾下
- <servicename="AsyncService">
- <description>
- AsyncService
- </description>
-
<parametername
- server.asynchronous.AsynchronousService
- </parameter>
- <messageReceivers>
- <messageReceivermep="http://www.w3.org/2004/08/wsdl/in-out"
- class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
-
<messageReceivermep="http://www.w3.org/2004/08/wsdl/in-only"
- class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
- </messageReceivers>
- </service>
3. 客戶端程式碼:
- package client;
- import java.io.IOException;
- import javax.xml.namespace.QName;
- import org.apache.axis2.addressing.EndpointReference;
- import org.apache.axis2.client.Options;
- import org.apache.axis2.client.async.AxisCallback;
- import org.apache.axis2.context.MessageContext;
- import org.apache.axis2.rpc.client.RPCServiceClient;
- publicclass AsynTest {
- publicstaticvoid main(String[] args) throws IOException {
- String target = "http://localhost:8080/axis2/services/AsyncService";
- RPCServiceClient client = new RPCServiceClient();
- Options options = client.getOptions();
- options.setManageSession(true);
- EndpointReference epr = new EndpointReference(target);
- options.setTo(epr);
- QName qname = new QName("http://asynchronous.server", "execute");
- //指定呼叫的方法和傳遞引數資料,及設定返回值的型別
- client.invokeNonBlocking(qname, new Object[] {}, new AxisCallback() {
- publicvoid onMessage(MessageContext ctx) {
- System.out.println(ctx.getEnvelope());
- System.out.println("Message:" + ctx.getEnvelope().getFirstElement().getFirstElement().getFirstElement().getText());
- }
- publicvoid onFault(MessageContext ctx) {
- }
- publicvoid onError(Exception ex) {
- }
- publicvoid onComplete() {
- }
- });
- //斷點此處,檢視非同步結果
- System.out.println("非同步WebService");
- //阻止程式退出
- System.in.read();
- }
- }