Dubbo的异步调用

2019-08-15  本文已影响0人  奔跑的Robi

Dubbo调用的过程会有网络延时,处理耗时等,如果业务上对于调用结果并不实时依赖,可以使用异步调用的方式
Dubbo2.7开始所有的异步接口使用CompletableFuture为基础

直接使用异步接口方式

在服务端,先定义异步服务接口

public interface AsyncService {
    CompletableFuture<String> sayHello(String name);
}

引用服务的配置中可配置timeout

<dubbo:reference id="asyncService" timeout="10000" interface="com.alibaba.dubbo.samples.async.api.AsyncService"/>

调用过程:

// 调用直接返回CompletableFuture
CompletableFuture<String> future = asyncService.sayHello("async call request");
// 增加回调
future.whenComplete((v, t) -> {
    if (t != null) {
        t.printStackTrace();
    } else {
        System.out.println("Response: " + v);
    }
});
// 早于结果输出
System.out.println("Executed before response return.");

重载接口方式

如果代码中服务接口不想更改,可以在接口中重载一个默认方法,前提是使用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));
    }
}

注意

如果只是想异步调用,不关心返回值,可以设置return为false,减去创建Future对象的开销

<dubbo:method name="find" async="true" return="false" />
上一篇 下一篇

猜你喜欢

热点阅读