You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
publicinterfaceGreetingsService {
StringsayHi(Stringname);
// AsyncSignal is totally optional, you can use any parameter type as long as java allows your to do that.defaultCompletableFuture<String> sayHi(Stringname, AsyncSignalsignal) {
returnCompletableFuture.completedFuture(sayHi(name));
}
}
在 Dubbo 中发起异步调用
背景
从 2.7.0 开始,Dubbo 的所有异步编程接口开始以 CompletableFuture 为基础
基于 NIO 的非阻塞实现并行调用,客户端不需要启动多线程即可完成并行调用多个远程服务,相对多线程开销较小。
示例
使用 CompletableFuture 签名的接口
需要服务提供者事先定义 CompletableFuture 签名的服务,具体参见服务端异步执行接口定义:
注意接口的返回类型是
CompletableFuture<String>
。XML引用服务:
调用远程服务:
使用 RpcContext
在 consumer.xml 中配置:
调用代码:
或者,你也可以这样做异步调用:
重载服务接口
如果你只有这样的同步服务定义,而又不喜欢 RpcContext 的异步使用方式。
那还有一种方式,就是利用 Java 8 提供的 default 接口实现,重载一个带有 CompletableFuture 签名的方法。
有两种方式来实现:
你也可以设置是否等待消息发出: 1
sent="true"
等待消息发出,消息发送失败将抛出异常。sent="false"
不等待消息发出,将消息放入 IO 队列,即刻返回。如果你只是想异步,完全忽略返回值,可以配置
return="false"
,以减少 Future 对象的创建和管理成本:The text was updated successfully, but these errors were encountered: