在Spring Boot中配置线程池可以通过@Configuration注解一个配置类,然后使用@Bean注解来提供一个ThreadPoolTaskExecutor的实例。以下是一个配置线程池的例子:
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;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 核心线程数
executor.setMaxPoolSize(20); // 最大线程数
executor.setQueueCapacity(500); // 队列容量
executor.setKeepAliveSeconds(60); // 线程空闲时间
executor.setThreadNamePrefix("MyThreadPoolTaskExecutor-"); // 线程名前缀
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
executor.initialize();
return executor;
}
}在这个配置中,我们定义了线程池的核心线程数、最大线程数、队列容量、空闲时间以及线程名前缀。setRejectedExecutionHandler方法设置了当队列满了且没有空闲线程来处理任务时的策略,这里使用的是CallerRunsPolicy,意味着在执行器执行被拒绝时,当前的任务会在调用者线程中运行。
要在你的应用中使用这个线程池,你可以在你的服务类中使用@Async注解来指定使用这个线程池:
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async("threadPoolTaskExecutor")
public void executeAsyncTask() {
// 异步任务的逻辑
}
}在这个例子中,executeAsyncTask方法会在名为threadPoolTaskExecutor的线程池中异步执行。