[英]What advantage is there to using Spring @Async vs. CompleteableFuture directly?
您的应用程序由容器管理。 由于不鼓励你自己生成Thread
,你可以让容器注入一个托管的Executor
。
@Service
class MyService {
@Autowired
private Executor executor;
public CompletableFuture<?> compute() {
return CompletableFuture.supplyAsync(() -> /* compute value */, executor);
}
}
两者之间没有“ 对比 ”:这些是互补技术:
CompletableFuture
提供了一种链接异步计算不同阶段的便捷方式 - 比Spring的ListenableFuture
具有更大的灵活性; @Async
为您的后台任务和线程提供方便的管理,为执行程序提供标准的Spring配置。 但两者都可以合并( 从Spring 4.2开始 )。 假设您要将以下方法转换为返回CompletableFuture
的后台任务:
public String compute() {
// do something slow
return "my result";
}
你要做什么:
@EnableAsync
和Executor
bean配置应用程序 @Async
注释方法 CompletableFuture.completedFuture()
@Async
public CompletableFuture<String> computeAsync() {
// do something slow - no change to this part
// note: no need to wrap your code in a lambda/method reference,
// no need to bother about executor handling
return CompletableFuture.completedFuture("my result");
}
正如您所注意到的,您不必费心将后台任务提交给执行者:Spring会为您处理这些问题。 您只需将结果包装到已完成的CompletableFuture
以便签名与调用者期望的匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.