Spring Boot Tomcat默认线程数详解
目录
默认线程数配置
Spring Boot2默认配置
在Spring Boot 2.x版本中,Tomcat的默认线程池配置如下:
# 默认线程池配置
server.tomcat.threads.max=200 # 最大线程数
server.tomcat.threads.min-spare=10 # 最小空闲线程数
server.tomcat.max-connections=8192 # 最大连接数
server.tomcat.accept-count=100 # 等待队列大小
Spring Boot3默认配置
在Spring Boot 3.x版本中,配置略有调整:
# Spring Boot3.x 默认配置
server.tomcat.threads.max=200 # 最大线程数
server.tomcat.threads.min-spare=10 # 最小空闲线程数
server.tomcat.connection-timeout=20# 连接超时时间(ms)
线程池核心参数
| 参数 | 默认值 | 说明 |
|---|---|---|
threads.max |
20大工作线程数 | |
threads.min-spare |
10 | 最小空闲线程数 |
max-connections |
8192 最大连接数 | |
accept-count |
100大小 | |
connection-timeout |
20000接超时时间(ms) |
线程池参数详解
###1最大线程数 (threads.max)
// Tomcat线程池配置源码示例
public class TomcatThreadPoolConfig[object Object]
@Value("${
server.tomcat.threads.max:200) private int maxThreads;
@Bean
public ThreadPoolTaskExecutor tomcatThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 核心线程数
executor.setMaxPoolSize(maxThreads); // 最大线程数
executor.setQueueCapacity(10); // 队列容量
executor.setThreadNamePrefix("tomcat-");
executor.initialize();
return executor;
}
}
性能影响:
- 过高:线程上下文切换开销大,内存占用高
- 过低:并发处理能力不足,请求排队时间长
- 建议:根据CPU核心数和业务特点调整
2. 最小空闲线程数 (threads.min-spare)
// 空闲线程管理
@Component
public class ThreadPoolMonitor {
@Autowired
private ThreadPoolTaskExecutor executor;
@Scheduled(fixedRate = 30030一次
public void monitorThreadPool() {
int activeCount = executor.getActiveCount();
int poolSize = executor.getPoolSize();
int corePoolSize = executor.getCorePoolSize();
log.info(线程池状态 - 活跃线程: [object Object]大小: {
}, 核心线程: {
}",
activeCount, poolSize, corePoolSize);
// 如果活跃线程数低于核心线程数,说明负载较轻
if (activeCount < corePoolSize * 0.5[object Object] log.info("当前负载较轻,可以考虑减少线程数");
}
}
}
3. 连接超时时间 (connection-timeout)
// 连接超时处理
@Configuration
public class TomcatConfig[object Object]
@Bean
public TomcatServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
@Override
protected void customizeConnector(Connector connector)[object Object] connector.setProperty(connectionTimeout", "20000");
connector.setProperty("maxConnections", "8192");
connector.setProperty("acceptCount", "100); }
};
}
}
配置方法
1. application.properties 配置
# 基础线程池配置
server.tomcat.threads.max=200rver.tomcat.threads.min-spare=10
server.tomcat.max-connections=8192rver.tomcat.accept-count=100.tomcat.connection-t



被折叠的 条评论
为什么被折叠?



