Dubbo調(diào)用的過程會有網(wǎng)絡(luò)延時,處理耗時等审磁,如果業(yè)務(wù)上對于調(diào)用結(jié)果并不實時依賴宦焦,可以使用異步調(diào)用的方式
Dubbo2.7開始所有的異步接口使用CompletableFuture為基礎(chǔ)
直接使用異步接口方式
在服務(wù)端,先定義異步服務(wù)接口
public interface AsyncService {
CompletableFuture<String> sayHello(String name);
}
引用服務(wù)的配置中可配置timeout
<dubbo:reference id="asyncService" timeout="10000" interface="com.alibaba.dubbo.samples.async.api.AsyncService"/>
調(diào)用過程:
// 調(diào)用直接返回CompletableFuture
CompletableFuture<String> future = asyncService.sayHello("async call request");
// 增加回調(diào)
future.whenComplete((v, t) -> {
if (t != null) {
t.printStackTrace();
} else {
System.out.println("Response: " + v);
}
});
// 早于結(jié)果輸出
System.out.println("Executed before response return.");
重載接口方式
如果代碼中服務(wù)接口不想更改,可以在接口中重載一個默認(rèn)方法拙泽,前提是使用jdk1.8+
public interface GreetingsService {
String sayHi(String name);
// AsyncSignal is totally optional, you can use any parameter type as long as java allows your to do that.
default CompletableFuture<String> sayHi(String name, AsyncSignal signal) {
return CompletableFuture.completedFuture(sayHi(name));
}
}
注意
如果只是想異步調(diào)用,不關(guān)心返回值,可以設(shè)置return為false沐旨,減去創(chuàng)建Future對象的開銷
<dubbo:method name="find" async="true" return="false" />