SpringBoot Tomcat配置
SpringBoot 提供完善的 Tomcat 配置选项。
基础配置
YAML
server:
port: 8080 # 服务端口
servlet:
context-path: /app # 应用上下文路径
tomcat:
uri-encoding: UTF-8 # URI编码
端口配置方式
YAML
# application.yml
server:
port: 8080
Bash
# 命令行参数
java -jar app.jar --server.port=9090
# 环境变量
SERVER_PORT=9090 java -jar app.jar
线程池配置
YAML
server:
tomcat:
threads:
max: 200 # 最大工作线程数
min-spare: 10 # 最小空闲线程数
线程数计算建议:
YAML
max-threads = CPU核心数 * 200
min-spare = CPU核心数 * 10
连接配置
YAML
server:
tomcat:
max-connections: 10000 # 最大连接数
accept-count: 100 # 接收队列长度
connection-timeout: 20000 # 连接超时(ms)
| 参数 | 默认值 | 说明 |
|---|---|---|
| max-connections | 8192 | 同时处理的连接数 |
| accept-count | 100 | 等待队列长度 |
| connection-timeout | 20000 | 连接空闲超时 |
访问日志配置
YAML
server:
tomcat:
accesslog:
enabled: true
directory: logs
prefix: access_log
suffix: .log
file-date-format: .yyyy-MM-dd
pattern: '%h %l %u %t "%r" %s %b %D'
日志格式字段说明:
| 字段 | 含义 |
|---|---|
| %h | 远程主机IP |
| %u | 用户名 |
| %t | 时间戳 |
| %r | 请求行 |
| %s | 状态码 |
| %b | 响应大小 |
| %D | 处理时间(ms) |
错误页面配置
Java
server:
error:
path: /error
whitelabel:
enabled: false # 禁用默认错误页面
自定义错误页面:
Java
@Controller
public class ErrorController {
@RequestMapping("/error")
public String handleError() {
return "error/500";
}
}
编程式配置
YAML
@Configuration
public class TomcatConfig {
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory>
tomcatCustomizer() {
return factory -> {
factory.addConnectorCustomizers(connector -> {
connector.setProperty("maxConnections", "5000");
connector.setProperty("connectionTimeout", "10000");
});
};
}
}
常用配置汇总
text
server:
port: 8080
servlet:
context-path: /
encoding:
charset: UTF-8
enabled: true
force: true
tomcat:
max-connections: 10000
accept-count: 100
threads:
max: 200
min-spare: 10
connection-timeout: 20000
uri-encoding: UTF-8
accesslog:
enabled: false
生产环境建议根据实际负载调整线程池和连接数参数。
要点总结
- server.port配置端口
- threads.max/min-spare配置线程池
- max-connections配置最大连接数
- accesslog配置访问日志
- 命令行参数可覆盖配置文件
📝 发现内容有误?点击此处直接编辑