林鱼
2025-9-24 16:47:25
Spring Boot 中使用线程池的示例
在 Spring Boot 应用中,线程池常用于处理异步任务、提高并发性能或执行耗时操作而不阻塞主线程。下面是一个完整的示例:
1. 配置线程池
首先,在配置类中定义线程池:- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.scheduling.annotation.EnableAsync;
- import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
- import java.util.concurrent.Executor;
- @Configuration
- @EnableAsync
- public class AsyncConfig {
-
- @Bean(name = "taskExecutor")
- public Executor taskExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(5); // 核心线程数
- executor.setMaxPoolSize(10); // 最大线程数
- executor.setQueueCapacity(100); // 队列容量
- executor.setThreadNamePrefix("Async-Thread-"); // 线程名前缀
- executor.initialize();
- return executor;
- }
- }
复制代码 2. 创建异步服务
创建一个使用线程池的服务:- import org.springframework.scheduling.annotation.Async;
- import org.springframework.stereotype.Service;
- @Service
- public class EmailService {
- // 使用指定线程池执行
- @Async("taskExecutor")
- public void sendEmail(String to, String content) {
- // 模拟耗时操作
- try {
- System.out.println(Thread.currentThread().getName() + " 开始发送邮件给: " + to);
- Thread.sleep(2000); // 模拟发送邮件耗时
- System.out.println("邮件发送成功: " + content);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- System.out.println("邮件发送被中断");
- }
- }
- }
复制代码 3. 控制器调用
创建一个控制器来触发异步任务:- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- public class EmailController {
- @Autowired
- private EmailService emailService;
- @GetMapping("/send")
- public String sendEmails() {
- for (int i = 0; i < 10; i++) {
- emailService.sendEmail("user" + i + "@example.com", "测试邮件内容 " + i);
- }
- return "邮件发送请求已提交";
- }
- }
复制代码 4. 实际应用场景
这个例子展示了线程池在以下场景中的应用:
- 批量发送邮件/短信:避免阻塞主线程,提高响应速度
- 日志记录:异步记录日志不影响主业务流程
- 数据导出:耗时的Excel导出操作
- 第三方API调用:异步调用外部服务
- 定时任务:使用 @Scheduled 注解配合线程池执行定时任务
5. 其他线程池使用方式
除了 @Async 注解,还可以直接使用线程池:- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
- import org.springframework.stereotype.Service;
- @Service
- public class ReportService {
-
- @Autowired
- private ThreadPoolTaskExecutor taskExecutor;
-
- public void generateReports() {
- for (int i = 0; i < 20; i++) {
- final int reportId = i;
- taskExecutor.execute(() -> {
- System.out.println(Thread.currentThread().getName() + " 生成报表: " + reportId);
- // 模拟报表生成
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- });
- }
- }
- }
复制代码 这个示例展示了如何在 Spring Boot 应用中配置和使用线程池来处理异步任务,提高应用性能。
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
|
|
|
相关推荐
|
|