异步调用,
对于 Provider 端不需要做特别的配置。
Consumer 配置:
<dubbo:reference id="asyncService" interface="com.x.x.AsyncService">
<dubbo:method name="testAsync" async="true"/>
</dubbo:reference>
Consumer 端发起调用:
String result = asyncService.testAsync("samples");// 这里的返回值为空,请不要使用
Future<String> future = RpcContext.getContext().getFuture();
... // 业务线程可以开始做其他事情
result = future.get(); // 阻塞需要获取异步结果时,也可以使用 get(timeout, unit) 设置超时时间
Dubbo Consumer端发起调用后,同时通过RpcContext.getContext().getFuture()获取跟返回结果关联的Future对象,然后就可以开始处理其他任务;当需要这次异步调用的结果时,可以在任意时刻通过future.get(timeout)来获取。
一些特殊场景下,为了尽快调用返回,可以设置是否等待消息发出:
sent="true" 等待消息发出,消息发送失败将抛出异常;
sent="false" 不等待消息发出,将消息放入 IO 队列,即刻返回。
return="false" 完全忽略是否返回
<dubbo:method name="testAsync" async="true" sent="true" />
或者
<dubbo:method name="testAsync" async="true" return="false"/>
默认是sent="false"。