首页 > 代码库 > Axis2发布webservice(4)—webservice的异步调用
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 one rror(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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。