当前位置: 首页 > news >正文

Spring Boot 异步编程

在 Spring Boot 中,异步编程可以显著提高应用程序的性能和响应能力,特别是在处理一些耗时的操作时。下面将详细介绍 Spring Boot 异步编程中异步方法的使用、线程池配置以及异步任务的监控与管理。

1. 异步方法的使用

步骤 1:启用异步支持

在 Spring Boot 主应用类上添加 @EnableAsync 注解来启用异步方法的支持。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class AsyncApplication {
    public static void main(String[] args) {
        SpringApplication.run(AsyncApplication.class, args);
    }
}
步骤 2:创建异步方法

在需要异步执行的方法上添加 @Async 注解。注意,异步方法必须是公共方法,并且不能在同一个类中调用自身的异步方法(因为 Spring 的 AOP 代理机制)。

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

import java.util.concurrent.CompletableFuture;

@Service
public class AsyncService {

    @Async
    public CompletableFuture<String> asyncMethod() throws InterruptedException {
        Thread.sleep(2000); // 模拟耗时操作
        return CompletableFuture.completedFuture("Async method completed");
    }
}
步骤 3:调用异步方法

在另一个服务或控制器中调用异步方法。

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

import java.util.concurrent.CompletableFuture;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/async")
    public String asyncRequest() throws InterruptedException {
        CompletableFuture<String> future = asyncService.asyncMethod();
        // 可以继续执行其他任务
        return "Request received, async method is processing";
    }
}

2. 线程池配置

默认情况下,Spring Boot 使用一个简单的线程池来执行异步任务。但是,为了更好地控制线程池的行为,我们可以自定义线程池。

步骤 1:创建线程池配置类
import org.springframework.context.annotation.Bean;
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
    @Bean(name = "asyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5); // 核心线程数
        executor.setMaxPoolSize(10); // 最大线程数
        executor.setQueueCapacity(25); // 队列容量
        executor.setThreadNamePrefix("AsyncThread-"); // 线程名前缀
        executor.initialize();
        return executor;
    }
}
步骤 2:使用自定义线程池

在异步方法上指定使用自定义的线程池。

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

import java.util.concurrent.CompletableFuture;

@Service
public class AsyncService {

    @Async("asyncExecutor")
    public CompletableFuture<String> asyncMethod() throws InterruptedException {
        Thread.sleep(2000); // 模拟耗时操作
        return CompletableFuture.completedFuture("Async method completed");
    }
}

3. 异步任务的监控与管理

监控任务状态

可以使用 CompletableFuture 来监控异步任务的状态。

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

import java.util.concurrent.CompletableFuture;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/async")
    public String asyncRequest() throws InterruptedException {
        CompletableFuture<String> future = asyncService.asyncMethod();
        // 检查任务是否完成
        if (future.isDone()) {
            return "Async method completed: " + future.get();
        } else {
            return "Request received, async method is still processing";
        }
    }
}
管理任务

可以使用 CompletableFuture 的一些方法来管理异步任务,例如取消任务。

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

import java.util.concurrent.CompletableFuture;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/async")
    public String asyncRequest() throws InterruptedException {
        CompletableFuture<String> future = asyncService.asyncMethod();
        // 取消任务
        future.cancel(true);
        return "Async method cancelled";
    }
}

通过以上步骤,可以在 Spring Boot 中实现异步编程,包括异步方法的使用、线程池的配置以及异步任务的监控与管理。


文章转载自:

http://hK8NDkck.bkpbm.cn
http://XY1EZT9G.bkpbm.cn
http://PZhgXLAW.bkpbm.cn
http://4FBgNZ4O.bkpbm.cn
http://XDAvE5BL.bkpbm.cn
http://EoE9lKCz.bkpbm.cn
http://zNekj4D8.bkpbm.cn
http://YLPIYgAN.bkpbm.cn
http://5BOQm3JK.bkpbm.cn
http://hSHFba2S.bkpbm.cn
http://5axElebf.bkpbm.cn
http://blPRYzPf.bkpbm.cn
http://rXzlgnDD.bkpbm.cn
http://F16CBGJG.bkpbm.cn
http://jNlNZkLy.bkpbm.cn
http://OGOdxdSk.bkpbm.cn
http://auxp8dhf.bkpbm.cn
http://pWaT1seF.bkpbm.cn
http://jpWBE7ku.bkpbm.cn
http://ZGiV8T3r.bkpbm.cn
http://CUQAASOs.bkpbm.cn
http://FKREZvLP.bkpbm.cn
http://YGmoM40H.bkpbm.cn
http://lS2SjQRR.bkpbm.cn
http://XDtxNcOL.bkpbm.cn
http://1Uu4t9II.bkpbm.cn
http://UX5fB9NJ.bkpbm.cn
http://TNdLHkbY.bkpbm.cn
http://kNOz7L81.bkpbm.cn
http://RO3cAY1t.bkpbm.cn
http://www.dtcms.com/a/46058.html

相关文章:

  • 大语言模型学习--LangChain
  • 6. 自动关闭文件
  • 知识图谱neo4j+vue+flask课程在线学习系统
  • 怎么下载安装yarn
  • Hive-05之查询 分组、排序、case when、 什么情况下Hive可以避免进行MapReduce
  • 【计算机网络基础】-------计算机网络概念
  • postgresql源码学习(60)—— VFD的作用及机制
  • 大模型function calling:让AI函数调用更智能、更高效
  • 六十天前端强化训练之第七天CSS预处理器(Sass)案例:变量与嵌套系统详解
  • 铁锈生锈检测数据集VOC+YOLO格式600张1类别
  • SSH密码更改
  • 【HTTP】解码网络通信的奥秘:HTTP,IP 地址,端口,DNS及NAT地址转换的协同之舞
  • The “Rule-of-Zero“ should be followed (s4963)
  • 【Envi遥感图像处理】014:影像非监督分类
  • JS宏案例:多项式回归
  • 数据集笔记:新加坡 地铁(MRT)和轻轨(LRT)票价
  • Spark核心之01:架构部署、sparkshell、程序模板
  • 前端面试题最新版
  • DeepSeek + dify 搭建本地知识库
  • DifyでOracle Base Database Service(23ai)を利用する設定手順
  • 1114棋盘问题acwing(深度优先搜索)
  • 机器学习的三个基本要素
  • Docker入门指南:Windows下docker配置镜像源加速下载
  • 火山引擎AI一体机-DeepSeek版来了
  • 代码随想录算法【Day60】
  • 数据结构(初阶)(七)----树和二叉树(前中后序遍历)
  • 【2025-03-02】基础算法:二叉树 相同 对称 平衡 右视图
  • 前端控制器模式
  • QT-对象树
  • partner‘127.0.0.1:3200‘ not reached