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

我认为第一个选项1提供了足够的异步方法。
但是,像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