异步执行
Dubbo 服务提供者的异步执行
此文档不再维护。您当前正在查看快照版本。如果您想查看文档的最新版本,请参阅 最新版本.
提供者端的异步执行将阻塞的业务从 Dubbo 的内部线程池切换到业务定义的线程,避免过度占用 Dubbo 线程池,并有助于避免不同服务之间的相互影响。异步执行相当于节省资源或提高 RPC 响应性能,因为如果业务执行需要阻塞,总会有一个线程负责执行。
注意
提供者端的异步执行和消费者端的异步调用是相互独立的,您可以以任何正交组合配置两端
- 消费者同步 - 提供者同步
- 消费者异步 - 提供者同步
- 消费者同步 - 提供者异步
- 消费者异步 - 提供者异步
定义 CompletableFuture 签名的接口
服务接口定义
public interface AsyncService {
CompletableFuture<String> sayHello(String name);
}
服务实现
public class AsyncServiceImpl implements AsyncService {
@Override
public CompletableFuture<String> sayHello(String name) {
RpcContext savedContext = RpcContext. getContext();
// It is recommended to provide a custom thread pool for supplyAsync and avoid using the JDK public thread pool
return CompletableFuture. supplyAsync(() -> {
System.out.println(savedContext.getAttachment("consumer-key1"));
try {
Thread. sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "async response from provider.";
});
}
}
通过 return CompletableFuture.supplyAsync()
,业务执行已从 Dubbo 线程切换到业务线程,避免了 Dubbo 线程池的阻塞。
使用 AsyncContext
Dubbo 提供了一个类似于 Servlet 3.0 的异步接口 AsyncContext
,它也可以在提供者端实现异步执行,而无需 CompletableFuture 签名接口。
服务接口定义
public interface AsyncService {
String sayHello(String name);
}
服务暴露与普通服务完全相同
<bean id="asyncService" class="org.apache.dubbo.samples.governance.impl.AsyncServiceImpl"/>
<dubbo:service interface="org.apache.dubbo.samples.governance.api.AsyncService" ref="asyncService"/>
服务实现
public class AsyncServiceImpl implements AsyncService {
public String sayHello(String name) {
final AsyncContext asyncContext = RpcContext. startAsync();
new Thread(() -> {
// If you want to use the context, it must be executed in the first sentence
asyncContext.signalContextSwitch();
try {
Thread. sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// write back the response
asyncContext.write("Hello " + name + ", response from provider.");
}).start();
return null;
}
}
上次修改时间:2023 年 1 月 2 日:增强 en 文档 (#1798) (95a9f4f6c1c)