异步调用只能在消费端配置
异步调用
基于 NIO 的非阻塞实现并行调用,客户端不需要启动多线程即可完成并行调用多个远程服务,相对多线程开销较小。
1、配置xml,只需要在reference里面新增async=true即可。
<dubbo:reference interface="com.hdd.api.IHelloWorld" id="helloWorld" cache="lru" timeout="5000" async="true"></dubbo:reference>
2、代码调用
public void testAsync() throws InterruptedException, ExecutionException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
IHelloWorld helloWorld = (IHelloWorld) applicationContext.getBean("helloWorld");
long start = System.currentTimeMillis();
//此时会立即返回null,同时设置Future到RpcContext中
String name = helloWorld.get("helloWorld ");
System.out.println("future.get()前:name:" + name);
//获取Future,通过get方法获取返回值
Future<String> future = RpcContext.getContext().getFuture();
//模拟本地操作需要4秒
Thread.sleep(4000);
String result = "local operator";
//获得真正的返回值,线程wait,如果服务有返回值,会调用notify
name = future.get();
System.out.println("future.get()后:name:" + name);
long end = System.currentTimeMillis();
System.out.println(name + result + ",用时:" + (end - start)/1000);
}