提升基于 Spring Boot 的 Web 项目并发量需要从 应用优化、数据库调优、缓存策略、异步处理、水平扩展 等多方面综合改进。以下是具体方案和实践建议:
• 避免阻塞操作:减少同步锁、长事务、大文件处理等耗时操作。
• 优化 SQL 查询:避免 N+1
查询,使用索引,减少全表扫描。
• 复用对象:避免频繁创建大对象(如 JSON 解析工具),使用线程安全对象池。
• 调整 Web 服务器线程池(如 Tomcat):
# application.yml
server:
tomcat:
max-connections: 8192 # 最大连接数
accept-count: 100 # 等待队列长度
threads:
max: 200 # 最大工作线程数
min-spare: 10 # 最小空闲线程数
• 自定义异步线程池:使用 @Async
处理非核心业务(如日志、邮件)。
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 核心线程数
executor.setMaxPoolSize(50); // 最大线程数
executor.setQueueCapacity(100); // 队列容量
executor.setThreadNamePrefix("Async-");
executor.initialize();
return executor;
}
}
• 使用 Spring WebFlux 替代传统 Servlet 模型,支持非阻塞 IO,适用于高并发场景。
• 使用高性能连接池(如 HikariCP)并合理配置:
spring:
datasource:
hikari:
maximum-pool-size: 20 # 最大连接数(根据数据库配置调整)
connection-timeout: 3000 # 连接超时时间(ms)
idle-timeout: 60000 # 空闲连接超时时间
• 主从架构:写操作走主库,读操作走从库。
• 分库分表:使用 ShardingSphere 或 MyCAT 拆分大表。
• 使用慢查询日志定位低效 SQL。
• 避免 SELECT *
,减少数据传输量。
• 对高频查询字段建立索引,但避免过度索引。
• 使用 Caffeine 缓存热点数据:
@Bean
public Cache<String, Object> caffeineCache() {
return Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(1000)
.build();
}
• 使用 Redis 或 Memcached 缓存共享数据,减少数据库压力。
@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) { ... }
• 对空值缓存,避免缓存穿透。
• 使用互斥锁或 Redis 的 SETNX
防止缓存击穿。
• 设置随机过期时间,避免缓存雪崩。
• 使用 @Async
异步执行耗时任务(如发送短信、记录日志):
@Async("taskExecutor")
public void asyncSendEmail(String email) { ... }
• 使用 RabbitMQ 或 Kafka 缓冲高并发请求:
@RabbitListener(queues = "order_queue")
public void processOrder(Order order) { ... }
• 通过 Nginx 或 Spring Cloud Gateway 分发请求到多个服务实例:
# nginx.conf
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}
server {
location / {
proxy_pass http://backend;
}
}
• 使用 Redis 存储 Session 数据,确保服务可横向扩展。
• 使用 Docker + Kubernetes 动态扩缩容实例。
• 提升传输效率,减少延迟。
# application.yml
server:
http2:
enabled: true
• 启用 GZIP 压缩:
server:
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,application/json
• 使用 Spring Boot Actuator + Prometheus + Grafana 监控 JVM、数据库、缓存等指标。
• 分析 GC 日志,优化 JVM 参数(如堆大小、垃圾回收器)。
• 使用 JMeter 或 Gatling 模拟高并发场景,找出瓶颈。
提升并发量的核心思路:
建议结合监控工具逐步优化,避免过度设计。例如,先优化数据库和缓存,再引入异步和消息队列,最后考虑水平扩展。