微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

异步调用Webservice

异步,说到异步需要首先将以下同步。同步就是代码按照顺序执行,当前面的代码的请求没有正常返回结果的情况下,后面的代码是不能运行。而异步正好和这点不同,异步是代码运行后,不管当前的请求是否返回结果,后面的代码都会继续运行。


1.   编写服务端代码

      

public class AsynchronousService {

	public String execute() {
		System.out.println("正在执行此代码……");
		// 延迟5秒后,返回结果
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printstacktrace();
		}
		return "完成";
	}
}

2.   编写services.xml代码,打包并发布至对应文件夹下

 

<service name="AsyncService">
	<description>
		AsyncService
   	</description>
	<parameter name="ServiceClass">
		server.asynchronous.AsynchronousService
   	</parameter>
	<messageReceivers>
		<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
			class="org.apache.axis2.rpc.receivers.RPcmessageReceiver" />
		<messageReceiver mep="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;

public class AsynTest {

	
	public static void 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() {
			
			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("异步WebService");
		//阻止程序退出
        system.in.read();
	}
	
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐