CompletableFuture VS @Async

问题描述 投票:0回答:1

我的英语不好。

我使用的是异步方法。

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

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

java spring-boot asynchronous completable-future
1个回答
1
投票

选项2是异步做了两次。

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

相反,你可以写。

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

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

在这里阅读更多关于Spring的Async。https:/www.baeldung.comspring-async

© www.soinside.com 2019 - 2024. All rights reserved.