详解SpringBoot中异步请求的实现与并行执行

 更新时间:2024年02月06日 08:07:33   作者:一只爱撸猫的程序猿  
这篇文章主要为大家详细介绍了在SpringBoot中如何是实现异步请求、并行执行,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

在Spring Boot中实现异步请求、并行执行,可以使用@Async注解来定义异步方法,同时使用FutureCompletableFuture或其他异步处理机制来处理异步结果和回调。以下是实现这一功能的几个步骤:

开启异步支持

首先,需要在Spring Boot应用中开启异步支持。这可以通过在一个配置类上添加@EnableAsync注解来实现。AsyncConfig 类开启异步支持并自定义Executor

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("Async-");
        executor.initialize();
        return executor;
    }
}

定义异步服务

然后,定义一个服务类,并在其中的方法上使用@Async注解来标记它们为异步方法。这里可以返回FutureCompletableFutureListenableFuture等,以便处理异步结果。

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class AsyncService {

    @Async
    public CompletableFuture<String> processAsync() {
        // 模拟异步任务
        try {
            Thread.sleep(1000);
            return CompletableFuture.completedFuture("单个任务执行完成");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return CompletableFuture.failedFuture(e);
        }
    }

    @Async
    public CompletableFuture<String> processAsyncParallel(int taskNumber) {
        // 模拟异步任务
        try {
            Thread.sleep(1000); // 假设这是耗时操作
            return CompletableFuture.completedFuture("任务 #" + taskNumber + " 执行完成");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return CompletableFuture.failedFuture(e);
        }
    }

    public List<CompletableFuture<String>> executeTasksInParallel() {
        List<CompletableFuture<String>> futures = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            futures.add(processAsyncParallel(i));
        }
        return futures;
    }
}

在Controller中调用并行执行方法并等待所有任务完成

AsyncController中,我们将添加一个映射来启动并行任务并等待它们全部完成。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/startParallelTasks")
    public String startParallelTasks() {
        List<CompletableFuture<String>> futures = asyncService.executeTasksInParallel();

        // 等待所有任务完成
        CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .thenApply(v -> futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList()));

        allDoneFuture.thenAccept(results -> results.forEach(System.out::println));

        return "并行任务开始执行";
    }

    @GetMapping("/waitForSpecificTask")
    public String waitForSpecificTask() throws Exception {
        CompletableFuture<String> future = asyncService.processAsync();

        // 等待特定任务完成
        String result = future.get(); // 阻塞直到任务完成

        return "特定任务完成,结果:" + result;
    }
}

说明

  • executeTasksInParallel方法在AsyncService中启动了多个并行的异步任务。这些任务通过CompletableFuture并行执行。
  • startParallelTasks中,我们使用CompletableFuture.allOf来等待所有任务完成。allOf返回一个新的CompletableFuture,该CompletableFuture在所有给定的CompletableFutures完成时完成。
  • waitForSpecificTask方法演示了如何等待一个特定的异步任务完成。使用CompletableFuture.get()方法可以阻塞当前线程直到异步任务完成,并获取结果。

代码示例展示了如何在Spring Boot应用中并行执行多个异步任务,并等待特定或所有任务的完成,充分利用@Async注解和CompletableFuture的能力来实现高效的异步编程模式。

到此这篇关于详解SpringBoot中异步请求的实现与并行执行的文章就介绍到这了,更多相关SpringBoot异步请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot2.0整合tk.mybatis异常解决

    SpringBoot2.0整合tk.mybatis异常解决

    本文主要介绍了SpringBoot2.0整合tk.mybatis异常,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-12-12
  • SpringBoot项目报错:"Error starting ApplicationContext...."解决办法

    SpringBoot项目报错:"Error starting ApplicationContext....

    这篇文章主要给大家介绍了关于SpringBoot项目报错:“Error starting ApplicationContext. To display the conditions report re-run ...”的解决办法,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2022-08-08
  • Java汉字转拼音工具类完整代码实例

    Java汉字转拼音工具类完整代码实例

    这篇文章主要介绍了java汉字转拼音工具类完整代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • Java实现inputstream流的复制代码实例

    Java实现inputstream流的复制代码实例

    这篇文章主要介绍了Java实现inputstream流的复制代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • SpringBoot实现RBAC权限校验模型的示例

    SpringBoot实现RBAC权限校验模型的示例

    本文主要介绍了SpringBoot实现RBAC权限校验模型的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-04-04
  • Java 死锁解决方案顺序锁和轮询锁

    Java 死锁解决方案顺序锁和轮询锁

    这篇文章主要介绍了Java 死锁解决方案顺序锁和轮询锁,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • 将SpringBoot项目无缝部署到Tomcat服务器的操作流程

    将SpringBoot项目无缝部署到Tomcat服务器的操作流程

    SpringBoot 是一个用来简化 Spring 应用初始搭建以及开发过程的框架,我们可以通过内置的 Tomcat 容器来轻松地运行我们的应用,本文给大家介绍 SpringBoot 项目部署到独立 Tomcat 服务器的操作流程,需要的朋友可以参考下
    2024-05-05
  • Java加载与存储指令之ldc与_fast_aldc指令

    Java加载与存储指令之ldc与_fast_aldc指令

    ldc指令将int、float、或者一个类、方法类型或方法句柄的符号引用、还可能是String型常量值从常量池中推送至栈顶。这一篇介绍一个虚拟机规范中定义的一个字节码指令ldc,另外还有一个虚拟机内部使用的字节码指令_fast_aldc。需要的盆友可参考下面文章的内容
    2021-09-09
  • Collections工具类_动力节点Java学院整理

    Collections工具类_动力节点Java学院整理

    Collections工具类提供了大量针对Collection/Map的操作。这篇文章主要介绍了Collections工具类_动力节点Java学院整理,需要的朋友可以参考下
    2017-04-04
  • Linux中Elasticsearch的安装详细步骤

    Linux中Elasticsearch的安装详细步骤

    这篇文章主要介绍了Linux中Elasticsearch的安装详细步骤,Elasticsearch(ES)是一种分布式、可扩展的搜索和分析引擎,基于Lucene构建,它支持实时数据处理、全文搜索、实时分析等多种功能,需要的朋友可以参考下
    2024-12-12

最新评论