CompletableFuture VS @Async



我英语不好。

我使用异步方法。

选项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和不使用它有什么区别。

我认为第一个Option1提供了足够多的异步方法
但是,像Option2那样使用它正确吗?

选项2异步完成两次。

如果您用e@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

最新更新