问题描述
我对此代码有疑问:
@Async
public CompletableFuture<String> doFoo() {
CompletableFuture<String> fooFuture = new CompletableFuture<>();
try {
String fooResult = longOp();
fooFuture.complete(fooResult);
} catch (Exception e) {
fooFuture.completeExceptionally(e);
}
return fooFuture;
}
问题是:doFoo是否仅在longOp完成(正确或异常)并因此返回已经完成的期货之后才返回fooFuture,还是Spring在执行主体之前做一些魔术并返回?如果代码在longOp()上阻塞,您将如何表示该计算将被馈送到执行程序?
The question is: does doFoo return fooFuture only after longOp has finished (either correctly or exceptionally) and is therefore returning already completed futures or is Spring doing some magic and returning before executing the body? If the code is blocking on longOp(), how would you express that the computation is being fed to an executor?
也许是这样吗?还有其他方法吗?
Perhaps this? Any other way?
@Async
public CompletableFuture<String> doFoo() {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
try {
String fooResult = longOp();
completableFuture.complete(fooResult);
} catch (Exception e) {
completableFuture.completeExceptionally(e);
}
});
return completableFuture;
}
推荐答案
Spring实际上完成了所有幕后工作,因此您不必自己创建CompletableFuture
.基本上,添加@Async
批注是 ,就像您调用原始方法(不使用批注)一样:
Spring actually does all of the work behind the covers so you don't have to create the CompletableFuture
yourself.Basically, adding the @Async
annotation is as if you called your original method (without the annotation) like:
CompletableFuture<User> future = CompletableFuture.runAsync(() -> doFoo());
关于第二个问题,为了将其提供给执行者,您可以在,如:
As for your second question, in order to feed it to an executor, you can specify the exectutor bean name in the value of the @Async
annotation, like so:
@Async("myExecutor")
public CompletableFuture<User> findUser(String usernameString) throws InterruptedException {
User fooResult = longOp(usernameString);
return CompletableFuture.completedFuture(fooResult);
}
上面的内容基本上就是以下,就像您调用原始方法一样:
The above would basically be the following as if you called your original method, like:
CompletableFuture<User> future = CompletableFuture.runAsync(() -> doFoo(), myExecutor);
您将使用该方法返回的CompletableFuture
进行所有exceptionally
逻辑.
And all of your exceptionally
logic you would do with the returned CompletableFuture
from that method.
这篇关于Spring @Async与CompletableFuture的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!