[英]CompletableFuture VS @Async
I am not good at English.我英语不好。
I use asynchronous methods.我使用异步方法。
Option 1选项1
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
return CompletableFuture.supplyAsync(() -> {
log.info("supplyAsync");
return (int)(price * 0.9);
}, threadPoolTaskExecutor);
}
Option 2选项 2
@Async
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
return CompletableFuture.supplyAsync(() -> {
log.info("supplyAsync");
return (int)(price * 0.9);
}, threadPoolTaskExecutor);
}
I wonder what the difference is between using @Async and not using it.我想知道使用 @Async 和不使用它之间有什么区别。
I think the first Option1 provides enough asynchronous methods.我认为第一个 Option1 提供了足够的异步方法。
However, is it correct to use it like Option2?但是,像Option2一样使用它是否正确?
Option 2 is asynchronous done twice.选项 2 是异步完成两次。
If you annotated a method withe @Async it will be executed by Spring asynchronously.如果您使用 @Async 注释方法,它将由 Spring 异步执行。 So you don't need to use the ThreadPoolExecutor by yourself.
所以你不需要自己使用ThreadPoolExecutor。
Instead you could write:相反,你可以写:
@Async
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
log.info("supplyAsync");
return new AsyncResult<Integer>((int)(price * 0.9));
}
Read more about Async with Spring here: https://www.baeldung.com/spring-async在此处阅读有关与 Spring 异步的更多信息: https://www.baeldung.com/spring-async
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.