繁体   English   中英

CompletableFuture VS @Async

[英]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 是异步完成两次。

如果您使用 @Async 注释方法,它将由 Spring 异步执行。 所以你不需要自己使用ThreadPoolExecutor。

相反,你可以写:

@Async
public CompletableFuture<Integer> getDiscountPriceAsync(Integer price) {
    log.info("supplyAsync");

    return new AsyncResult<Integer>((int)(price * 0.9)); 
}

在此处阅读有关与 Spring 异步的更多信息: https://www.baeldung.com/spring-async

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM