基於dubbo實現異步調用
增加consumer配置
這種方式很簡單,只需要在服務引用時增加dubbo:method配置即可,如下所示,其中name爲需要異步調用的方法名,async表示是否啓用異步調用。
<dubbo:reference id="asyncService" check="false" interface="com.alibaba.dubbo.demo.AsyncService" url="localhost:20880">
<dubbo:method name="sayHello" async="true" />
</dubbo:reference>
此時consumer端有3種調用方式:
由於配置了異步調用,因此此時直接調用將返回null:
String result = asyncService.sayHello("world");
通過RpcContext獲取Future對象,調用get方法時阻塞知道返回結果:
asyncService.sayHello("world");
Future<String> future = RpcContext.getContext().getFuture();
String result = future.get();
如果只想異步調用,不需要返回值,則可以配置 return=“false”,這樣可以避免Future對象的創建,此時RpcContext.getContext().getFuture()將返回null;