Dubbo支持异步调用的方式,摘自官网流程图
服务提供方:
@Service
@com.alibaba.dubbo.config.annotation.Service(version = "1.0.0",timeout = 10000)
public class AsyncServiceImpl implements AsyncService {
private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);
@Override
public String sayHello01() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
}
}
和正常请求服务没有区别,有区别的是消费端,引用服务的时候,设置async的值为true即可。
@Reference(version = "1.0.0",async = true)
private AsyncService asyncService;
@GetMapping("/getAsyncResult")
public Object getAsyncResult() throws ExecutionException, InterruptedException {
String result01 = asyncService.sayHello01();
logger.info("result01:"+result01);
// 拿到调用的Future引用,当结果返回后,会被通知和设置到此Future
Future<String> future = RpcContext.getContext().getFuture();
String result02=future.get();
return result02;
}
需要的是接口的返回值永远为null,只有通过Future中获取到的值才是服务返回的值,注解的方式将导致接口下所有的服务都是异步的;