一般情况下,我们使用同步方法(invokeBlocking)调用 axis2 接口,如果被调用的 WebService 方法长时间不返回,客户端将一直被阻塞,直到该方法返回为止。使用同步方法来调用 WebService 虽然很直观,但当 WebService 方法由于各种原因需要很长时间才能返回的话,就会使客户端程序一直处于等待状态,这样用户是无法忍受的。
当然,我们很容易就可以想到解决问题的方法,这就是多线程。解决问题的基本方法是将访问 WebService 的任务交由一个或多个线程来完成,而主线程并不负责访问 WebService。这样即使被访问的 WebService 方法长时间不返回,客户端仍然可以做其他的工作。我们可以管这种通过多线程访问 WebService 的方式称为异步访问。
package com.alfred.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 ServiceClient {
public static void main(String args[])
throws IOException {
sendAxis2();
}
/**
* 发送axis2的接口信息
*
* @throws IOException
*/
private static void sendAxis2()
throws IOException {
// 使用RPC方式调用WebService
RPCServiceClient serviceClient =
new RPCServiceClient();
Options options = serviceClient.getOptions();
// 指定调用WebService的URL
EndpointReference targetEPR =
new EndpointReference(
"
http://127.0.0.1:8080/awyb/services/mySoapService");
options.setTo(targetEPR);
// 指定sayHello方法的参数值,如果有多个,继续往后面增加即可
Object[] opAddEntryArgs =
new Object[] { "
alfred" };
// 在创建QName对象时,QName类的构造方法的第一个参数表示WSDL,文件的命名空间名,也就是<wsdl:definitions>元素的targetNamespace属性值
// 第二个参数是要调用的方法名
QName opAddEntry =
new QName("
http://service.alfred.com", "
sayHello");
serviceClient.invokeNonBlocking(opAddEntry, opAddEntryArgs,
new AxisCallback() {
public void onComplete() {}
public void onError(Exception arg0) {}
public void onFault(MessageContext arg0) {}
public void onMessage(MessageContext mc) {
// 输出返回值
System.out.println(mc.getEnvelope().getFirstElement()
.getFirstElement().getFirstElement().getText());
}
});
System.out.println("
异步调用!");
// 阻止程序退出
System.in.read();
}
}