标签:style blog http java color os
package com.hoo.service; public class AsynchronousService { public String execute() throws InterruptedException{ //让当前线程睡眠5钟,展示异步调用 Thread.sleep(5000); return "done"; } }
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
首先,生成该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
Axis2发布webservice(4)—webservice的异步调用,布布扣,bubuko.com
Axis2发布webservice(4)—webservice的异步调用
标签:style blog http java color os
原文地址:http://www.cnblogs.com/hewenwu/p/3863959.html