【问题标题】:CompletableFuture VS @AsyncCompletableFuture VS @Async
【发布时间】:2020-08-07 20:47:28
【问题描述】:

我英语不好。

我使用异步方法。

选项 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那样使用是否正确?

【问题讨论】:

标签: java spring-boot asynchronous completable-future


【解决方案1】:

选项 2 异步执行两次。

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

你可以写:

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

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

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

【讨论】:

  • 如果我的回答有帮助,请采纳。谢谢
  • 要返回 CompleteFuture,我必须使用 AsyncResult 的 complete() 方法。 --> return new AsyncResult((int) (price * 0.9)).completable();
  • @EddyKim,你也可以使用return CompletableFuture.completedFuture((int)(price * 0.9));
  • 我可以更新我的答案,但在此之前:你真的需要 CompletableFuture 吗?未来还不够好吗?
  • @DidierL 我喜欢你的评论!
猜你喜欢
  • 2019-07-18
  • 2016-12-09
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
相关资源
最近更新 更多