1.场景
基于 NIO 的非阻塞实现并行调用,客户端不需要启动多线程即可完成并行调用多个远程服务,相对多线程开销较小
2.在 consumer.xml 中配置
1 <dubbo:reference id="fooService" interface="com.alibaba.foo.FooService"> 2 <dubbo:method name="findFoo" async="true" /> 3 </dubbo:reference> 4 <dubbo:reference id="barService" interface="com.alibaba.bar.BarService"> 5 <dubbo:method name="findBar" async="true" /> 6 </dubbo:reference>
3.调用代码
1 // 此调用会立即返回null 2 fooService.findFoo(fooId); 3 // 拿到调用的Future引用,当结果返回后,会被通知和设置到此Future 4 Future<Foo> fooFuture = RpcContext.getContext().getFuture(); 5 6 // 此调用会立即返回null 7 barService.findBar(barId); 8 // 拿到调用的Future引用,当结果返回后,会被通知和设置到此Future 9 Future<Bar> barFuture = RpcContext.getContext().getFuture(); 10 11 // 此时findFoo和findBar的请求同时在执行,客户端不需要启动多线程来支持并行,而是借助NIO的非阻塞完成 12 13 // 如果foo已返回,直接拿到返回值,否则线程wait住,等待foo返回后,线程会被notify唤醒 14 Foo foo = fooFuture.get(); 15 // 同理等待bar返回 16 Bar bar = barFuture.get(); 17 18 // 如果foo需要5秒返回,bar需要6秒返回,实际只需等6秒,即可获取到foo和bar,进行接下来的处理。