java - CompletableFuture VS @Async

标签 java spring-boot asynchronous completable-future

我英语不好。

我使用异步方法。

选项 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)); 
}

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

关于java - CompletableFuture VS @Async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61405655/

相关文章:

java - Spring Data MongoDB 中的 INNER JOIN 集合

java smack 4.0.3库facebook登录错误

java - 将 ArrayList 转换为有序集(TreeSet)并返回

Java - 将日期格式的字符串从 SQL 数据库转换为日期对象以进行比较

node.js - 无法从 : https://nodejs. org/dist/v6.11.3/x64/node.exe 下载 Node.js:从服务器获取错误代码 404

c# - 在异步方法中省略异步和等待

c# - 使用异步等待从事件更新 UI

java - 如何针对部署在 Openshift(基于云的 Kubernetes)的 Elasticsearch 在 Spring Boot 上使用自签名证书实现 SSL

spring-boot - 从配置文件中获取断路器的实例

node.js - 将异步函数转换为同步函数