|
| 1 | +package com.github.kuangcp.pool; |
| 2 | + |
| 3 | +import org.apache.commons.lang3.concurrent.BasicThreadFactory; |
| 4 | +import org.springframework.context.annotation.Bean; |
| 5 | +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; |
| 6 | + |
| 7 | +import java.util.concurrent.ThreadPoolExecutor; |
| 8 | + |
| 9 | +/** |
| 10 | + * @author Kuangcp |
| 11 | + * 2025-05-13 15:12 |
| 12 | + */ |
| 13 | +public class SpringThreadPool { |
| 14 | + |
| 15 | + /** |
| 16 | + * 核心线程数 - 保持较小以减少资源消耗 |
| 17 | + */ |
| 18 | + private int corePoolSize = 10; |
| 19 | + |
| 20 | + /** |
| 21 | + * 最大线程数 - 考虑到LLM调用的IO密集特性 |
| 22 | + */ |
| 23 | + private int maxPoolSize = 20; |
| 24 | + |
| 25 | + /** |
| 26 | + * 队列容量 - 较大的队列用于缓冲请求 |
| 27 | + */ |
| 28 | + private int queueCapacity = 1000; |
| 29 | + |
| 30 | + /** |
| 31 | + * 线程空闲超时时间(秒) |
| 32 | + */ |
| 33 | + private int keepAliveSeconds = 300; |
| 34 | + |
| 35 | + /** |
| 36 | + * 是否等待所有任务完成后再关闭线程池 |
| 37 | + */ |
| 38 | + private boolean waitForTasksToCompleteOnShutdown = true; |
| 39 | + |
| 40 | + /** |
| 41 | + * 线程池关闭时等待任务完成的最长时间(秒) |
| 42 | + */ |
| 43 | + private int awaitTerminationSeconds = 60; |
| 44 | + |
| 45 | + @Bean(name = "llmThreadPool") |
| 46 | + public ThreadPoolTaskExecutor llmThreadPool() { |
| 47 | + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); |
| 48 | + |
| 49 | + // 核心配置 |
| 50 | + executor.setCorePoolSize(corePoolSize); |
| 51 | + executor.setMaxPoolSize(maxPoolSize); |
| 52 | + executor.setQueueCapacity(queueCapacity); |
| 53 | + executor.setKeepAliveSeconds(keepAliveSeconds); |
| 54 | + |
| 55 | + // 使用自定义的线程工厂,设置有意义的线程名称前缀 |
| 56 | + executor.setThreadFactory(new BasicThreadFactory.Builder() |
| 57 | + .namingPattern("llm-worker-%d") |
| 58 | + .daemon(true) // 设置为守护线程 |
| 59 | + .build()); |
| 60 | + |
| 61 | + // 设置拒绝策略为CallerRunsPolicy,防止任务丢失 |
| 62 | + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); |
| 63 | + |
| 64 | + // 优雅关闭配置 |
| 65 | + executor.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown); |
| 66 | + executor.setAwaitTerminationSeconds(awaitTerminationSeconds); |
| 67 | + |
| 68 | + // 初始化线程池 |
| 69 | + executor.initialize(); |
| 70 | + |
| 71 | + return executor; |
| 72 | + } |
| 73 | +} |
0 commit comments