我英语不好。
我使用异步方法。
选项 1
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
return CompletableFuture.supplyAsync(() -> {
log.info("supplyAsync");
return (int)(price * 0.9);
}, threadPoolTaskExecutor);
}
选项 2
@Async
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
return CompletableFuture.supplyAsync(() -> {
log.info("supplyAsync");
return (int)(price * 0.9);
}, threadPoolTaskExecutor);
}
我想知道使用 @Async 和不使用它有什么区别。
我认为第一个选项1提供了足够的异步方法。
但是,像Option2那样使用是否正确呢?
最佳答案
选项 2 异步执行两次。
如果你用 @Async 注释了一个方法,它将被 Spring 异步执行。所以你不需要自己使用ThreadPoolExecutor。
你可以写:
@Async
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
log.info("supplyAsync");
return new AsyncResult<Integer>((int)(price * 0.9));
}
在此处阅读有关 Async with Spring 的更多信息:https://www.baeldung.com/spring-async
关于java - CompletableFuture VS @Async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61405655/