在 Spring Boot 中创建线程池,可以使用 Java 提供的 ExecutorService
或 Spring 提供的 TaskExecutor
来管理线程池。下面是几种常见的方式来在 Spring Boot 应用中配置线程池:
1. 使用 ThreadPoolTaskExecutor
配置线程池
Spring 提供了 ThreadPoolTaskExecutor
,它是一个封装了 Java 原生线程池的类,并且集成了 Spring 的一些功能。
步骤:
- 创建线程池配置类,使用
ThreadPoolTaskExecutor
来配置线程池。 - 在服务类中注入
TaskExecutor
并使用。
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 ThreadPoolConfig {
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置线程池参数
executor.setCorePoolSize(10); // 核心线程数
executor.setMaxPoolSize(50); // 最大线程数
executor.setQueueCapacity(100); // 队列容量
executor.setThreadNamePrefix("myExecutor-"); // 线程名前缀
executor.initialize(); // 初始化线程池
return executor;
}
}
使用线程池:
一旦线程池配置完成,你就可以在需要执行异步任务的地方使用线程池。通过 @Async
注解来异步执行方法。
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Async("taskExecutor") // 使用指定的线程池
public void asyncMethod() {
System.out.println("异步执行的任务,线程名称:" + Thread.currentThread().getName());
}
}
2. 使用 Java 原生 ExecutorService
你也可以直接使用 Java 原生的 ExecutorService
来创建线程池。这种方式可以给你更大的灵活性。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Configuration
public class ExecutorServiceConfig {
@Bean
public ExecutorService executorService() {
// 创建一个固定大小的线程池
return Executors.newFixedThreadPool(10);
}
}
使用线程池:
import org.springframework.stereotype.Service;
import java.util.concurrent.ExecutorService;
@Service
public class MyService {
private final ExecutorService executorService;
public MyService(ExecutorService executorService) {
this.executorService = executorService;
}
public void submitTask() {
executorService.submit(() -> {
System.out.println("任务执行,线程名称:" + Thread.currentThread().getName());
});
}
}