一、异步调用
二、同步调用异步调用比较
同步调用:
异步调用:
三、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 中来发送对与我们来说没由影响,然后从架构跟资源的角度来讲,对我们的影响就大了,把连接层的资源跟应用层的程序运行状态绑定起来是由许多弊端的,假如在异步调用时,程序运行出现了异常,将会导致连接层的资源被一直占用,这样会极大的影响我们程序的,稳定性,可靠性,资源的使用跟性能。
四、异步调用实现
接用上一篇的例子,JAX-WS(三)构建简单webservice部署到tomcat上
先在工程目录下建一个binding.xml的文件:
<?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" wsdlLocation="http://localhost:8080/JaxwsWebServer/HelloService?wsdl"
xmlns="http://java.sun.com/xml/ns/jaxws">
<bindings node="wsdl:definitions">
<enableAsyncMapping>true</enableAsyncMapping>
</bindings>
</bindings>
用wsimport命令:
wsimport -b binding.xml -s ./src -d ./bin -p org.ccnt.jax.web.asyclient http://localhost:8080/JaxwsWebServer/HelloService?wsdl
生成如下文件:
新建类ClientAsyncMain调用:
package org.ccnt.jax.web.asyclient; import javax.xml.ws.Response; public class ClientAsyncMain { public static void main(String[] args) {
HelloService service = new HelloService();
Hello port = service.getHelloPort();
Response<SayResponse> 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
五、异步的另一种实现,回调
package org.ccnt.jax.web.asyclient; import java.util.concurrent.ExecutionException; import javax.xml.ws.AsyncHandler;
import javax.xml.ws.Response; public class ClientAsyncCallback { public static void main(String[] args) throws InterruptedException {
HelloService service = new HelloService();
Hello port = service.getHelloPort();
port.sayAsync("loull", new AsyncHandler<SayResponse>() {
@Override
public void handleResponse(Response<SayResponse> res) {
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