Axis2发布webservice(4)—webservice的异步调用
一,发布一个webservice,代码如下
package com.hoo.service; public class AsynchronousService { public String execute() throws InterruptedException{ //让当前线程睡眠5钟,展示异步调用 Thread.sleep(5000); return "done"; } }
二、发布Service,参见前面教程,不多讲
三、RPC方式异步调用:
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; public class AsynchronousServiceClient { public static void main(String[] args) throws IOException { String target = "http://localhost:8080/axis2/services/AsynchronousService"; RPCServiceClient client = new RPCServiceClient(); Options options = client.getOptions(); options.setManageSession(true); EndpointReference epr = new EndpointReference(target); options.setTo(epr); QName qname = new QName("http://service.hoo.com", "execute"); //指定调用的方法和传递参数数据,及设置返回值的类型,前面两个参数跟同步调用没区别,关键是后面一个参数,用到了AxisCallback类 client.invokeNonBlocking(qname, new Object[] {}, new AxisCallback() { public void onMessage(MessageContext ctx) { System.out.println(ctx.getEnvelope()); //获取返回值并打印 System.out.println("Message:" + ctx.getEnvelope().getFirstElement().getFirstElement().getFirstElement().getText()); } public void onFault(MessageContext ctx) { } public void onError(Exception ex) { } public void onComplete() { } }); System.out.println("Client:异步调用WebService"); //阻止程序退出 System.in.read(); } }
程序输出:
Client:异步调用WebService
<?xml version=‘1.0‘ encoding=‘utf-8‘?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><ns:executeResponse xmlns:ns="http://service.hoo.com"><ns:return>done</ns:return></ns:executeResponse></soapenv:Body></soapenv:Envelope>
Message:done
四、Stub类异步调用
首先,生成该webservice的wsdl文件,然后用wsdl文件生成Java源代码,方法参见http://www.cnblogs.com/hewenwu/p/3860083.html
五、编写客户端异步调用代码
package test; import java.io.IOException; import java.rmi.RemoteException; import org.apache.axis2.AxisFault; import com.hoo.service.AsynchronousServiceCallbackHandler; import com.hoo.service.AsynchronousServiceStub; import com.hoo.service.Execute; import com.hoo.service.ExecuteResponse; public class AsynchronousServiceClient { public static void main(String[] args) throws IOException { AsynchronousServiceStub stub = new AsynchronousServiceStub(); stub.startexecute(new Execute(), new MyCallback()); System.out.println("异步调用"); System.in.read(); } }
//必须重新定义一个继承自相应CallbackHandler的类并重写receiveResult方法才能在main中调用 class MyCallback extends AsynchronousServiceCallbackHandler{ @Override public void receiveResultexecute(ExecuteResponse result) { super.receiveResultexecute(result); System.out.println(result.get_return()); } }
输出结果:
异步调用
done
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。