簡體   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