異步通信對於服務端響應時間較長的方法是必須的,可以有效地利用客戶端的資源,在dubbo中,消費端<dubbp:method>經過 async="true"標識。html
<dubbo:reference id="xxx" ....>異步
<dubbo:method name="method1" async="true" />async
</dubbo:reference>線程
具體有三種方式:htm
一、NIO future主動獲取結果,返回結果放在RpcContext中接口
須要注意的是,因爲RpcContext是單例模式,因此每次調用完後,須要保存一個Future實例;如:事件
fooService.findFoo(fooId);
Future<Foo> fooFuture = RpcContext.getContext().getFuture();
barService.findBar(barId);
Future<Bar> barFuture = RpcContext.getContext().getFuture();
barService.findBar(barId);
Bar bar = barFuture.get();ci
二、經過回調(Callback)參數資源
Callback並非dubbo內部類或接口,而是由應用自定義的、實現了Serializable的接口;get
分兩步:1)服務提供者需在方法中聲明Callback參數,其後在Service實現中顯示地調用Callback的方法;
<dubbo:service ..>
<dubbo:method name="method1">
<dubbo:argument index="1" callback="true" /> #標識第二個參數是callback類型
</dubbo:method>
</dubbo:service>
2)Callback接口的實現類在消費端,當方法發生調用時,消費端會自動export一個Callback服務,在Rpc調用完成後,不能當即結束線程。
<dubbo:reference ...>
<dubbo:method name="method1" async="true">
</dubbo:reference>
三、事件通知(推薦)
這種方式更簡單,對服務提供方來說是透明的,包括配置和代碼上,均無需作任何改動。
消費端定義一個「通知者」的Spring Bean,指定方法的onreturn和onthrow事件action就能夠。 <bean id="notify" class="com.alibaba.dubbo.callback.implicit.NofifyImpl" /> <dubbo:reference ><dubbo:method name="method1" async="true" onreturn="notify.onreturn" onthrow="notify.onthrow" /> </dubbo:reference>