
异步调用:

三、jax-ws的同步和异步
在旧的基于JAX-RPC的webservice编程model中,是不支持异步的service 调用的,在最新的Jax-ws webservice 编程model中,加入了对webservice的异步调用的支持。
首先我来讲一下它的原理,大家不要以为在异步的调用下,从client到server 之间的soap message 流也是异步的,其实不是,Soap/Http 协议在同步跟异步的调用下是一样的,都是客户端的service在运行时打开一个connectin,发送请求,然后接收返回,这些都在同一个connection中。这种方式对我们有什么影响呢?从客户端程序的角度来讲,没有影响,客户端的编程模型是由WSDL中的messages跟port types 来定义的,只要这些东西没有改变,request 跟response是不是在同一个Tcp/ip 的session 中来发送对与我们来说没由影响,然后从架构跟资源的角度来讲,对我们的影响就大了,把连接层的资源跟应用层的程序运行状态绑定起来是由许多弊端的,假如在异步调用时,程序运行出现了异常,将会导致连接层的资源被一直占用,这样会极大的影响我们程序的,稳定性,可靠性,资源的使用跟性能。
四、异步调用实现
先在工程目录下建一个binding.xml的文件:
true
用wsimport命令:
wsimport -b binding.xml -s ./src -d ./bin -p org.ccnt.jax.web.asyclient http://localhost:8080/JaxwsWebServer/HelloService?wsdl
生成如下文件:

新建类ClientAsyncMain调用:
packageorg.ccnt.jax.web.asyclient;importjavax.xml.ws.Response;public classClientAsyncMain {public static voidmain(String[] args) {
HelloService service= newHelloService();
Hello port=service.getHelloPort();
Response sayAsync = port.sayAsync("loull");while (!sayAsync.isDone()) {
System.out.println("is not down");
}try{
SayResponse callNameResponse=sayAsync.get();
String message=callNameResponse.getReturn();
System.out.println("~~~" +message);
}catch(Exception exception) {
exception.printStackTrace();
}
}
}
结果:
...
is not down
is not down
is not down
is not down
is not down
is not down
is not down
is not down
is not down
is not down
is not down
is not down
is not down
is not down
is not down~~~hello, loull
五、异步的另一种实现,回调
packageorg.ccnt.jax.web.asyclient;importjava.util.concurrent.ExecutionException;importjavax.xml.ws.AsyncHandler;importjavax.xml.ws.Response;public classClientAsyncCallback {public static void main(String[] args) throwsInterruptedException {
HelloService service= newHelloService();
Hello port=service.getHelloPort();
port.sayAsync("loull", new AsyncHandler() {
@Overridepublic void handleResponse(Responseres) {
SayResponse response= null;try{
response=res.get();
String message=response.getReturn();
System.out.println(message);
}catch (InterruptedException |ExecutionException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
});for (int i=0; i<10; i++) {
System.out.println("Zzz...");
}
Thread.sleep(1500);
}
}
结果:
Zzz...
Zzz...
Zzz...
Zzz...
Zzz...
Zzz...
Zzz...
Zzz...
Zzz...
Zzz...
hello, loull
参考和扩展:
本文介绍了Java JAX-WS中异步调用Web服务的原理和实现方式,包括通过创建`binding.xml`文件并使用`wsimport`命令生成相关文件,以及两种不同的异步调用示例:一种是通过检查`Response`的完成状态,另一种是利用`AsyncHandler`进行回调处理。
410

被折叠的 条评论
为什么被折叠?



