当前位置: 首页 > news >正文

Spring Boot 调优的 12 个关键节点

数据库连接池调优:精准匹配系统资源

症状:
默认配置下,连接池资源使用不当,高并发时连接耗尽或排队。

常见误区:

spring:datasource:hikari:maximum-pool-size: 1000  # 设置过大connection-timeout: 30000  # 设置过长

推荐配置:

spring:datasource:hikari:maximum-pool-size: ${CPU核心数 * 2}minimum-idle: 5connection-timeout: 3000max-lifetime: 1800000idle-timeout: 600000

根据硬件环境(如 CPU 核心数)合理配置连接池,避免资源浪费。

JVM 参数优化:降低 GC 停顿带来的抖动

建议启动参数:

java-Xms4g-Xmx4g\
-XX:NewRatio=1\
-XX:+UseG1GC\
-XX:MaxGCPauseMillis=200\
-XX:InitiatingHeapOccupancyPercent=35\
-XX:+AlwaysPreTouch

将新生代与老年代等比设置,使用 G1 收集器,最大暂停时间控制在 200ms 内。

精简自动装配:去除不必要的组件

示例:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,SecurityAutoConfiguration.class
})

屏蔽当前未使用的自动装配组件,有助于提升应用启动速度与资源占用效率。

启用响应压缩:减少传输体积,提升响应速度

server:compression:enabled: truemime-types: text/html,text/xml,text/plain,text/css,text/javascript,application/jsonmin-response-size: 1024

启用 Gzip 压缩功能,尤其对接口返回大量 JSON 数据的场景效果明显。

接口参数校验:防止资源被恶意占用

@GetMapping("/products")
public PageResult<Product> list(@RequestParam @Max(100) int pageSize,@RequestParam @Min(1) int pageNum) {// ...
}

通过注解式参数验证,及时阻断不合理请求,保护服务端资源。

异步执行任务:提升吞吐,释放主线程

@Async("taskExecutor")
public CompletableFuture<List<Order>> process() {return CompletableFuture.completedFuture(doHeavyWork());
}@Bean("taskExecutor")
public Executor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(500);return executor;
}

适用于非实时或耗时较长的处理流程。

缓存机制接入:减少重复查询压力

@Cacheable(cacheNames = "products", key = "#id", cacheManager = "caffeineCacheManager")
public Product getProductDetail(Long id) {return productDao.getById(id);
}

使用 Caffeine 或 Redis 缓存,可有效减轻数据库负担,提升接口响应速度。

批量操作替代单条处理:成倍提升写入效率

@Transactional
public void batchInsert(List<Product> products) {jdbcTemplate.batchUpdate("INSERT INTO product(name,price) VALUES(?,?)",products,500,(ps, product) -> {ps.setString(1, product.getName());ps.setBigDecimal(2, product.getPrice());});
}

将频繁的单条操作合并为批处理,减少数据库连接与事务开销。

深度优化 SQL 与索引:保障查询效率

场景问题:

SELECT * FROM products WHERE category = '手机' AND price > 5000 ORDER BY create_time DESC;

优化建议:

① 联合索引:

ALTER TABLE products ADD INDEX idx_category_price_create (category, price, create_time);

② 覆盖索引:

仅查询索引字段:

SELECT id, category, price, create_time FROM products WHERE category ='手机'AND price > 5000 ORDERBY create_time DESC;

③ 避免函数索引失效:

错误:

WHERE DATE(create_time) = '2023-01-01'

正确:

WHERE create_time BETWEEN '2023-01-01 00:00:00' AND '2023-01-01 23:59:59'

④ 监控与分析:

SELECT*FROM sys.schema_index_statistics WHERE table_name ='products';

使用 EXPLAIN FORMAT=JSON 分析执行计划。

自定义线程池:应对高并发的可控策略

@Bean("customPool")
public Executor customThreadPool() {return new ThreadPoolExecutor(10,50,60, TimeUnit.SECONDS,new LinkedBlockingQueue<>(1000),new CustomThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());
}

杜绝默认线程池带来的资源不可控问题,自定义线程池策略更符合业务场景。

接口限流与熔断:抵御突发流量冲击

@SentinelResource(value = "orderQuery",blockHandler = "handleBlock",fallback = "handleFallback")
@GetMapping("/orders/{id}")
public Order getOrder(@PathVariable Long id) {return orderService.getById(id);
}public Order handleBlock(Long id, BlockException ex) {throw new RuntimeException("当前访问过多,请稍后再试");
}public Order handleFallback(Long id, Throwable t) {return Order.getDefaultOrder();
}

使用 Sentinel 实现服务保护机制,避免单点失控造成连锁故障。

全链路监控体系:问题诊断有据可依

management:endpoints:web:exposure:include: "*"metrics:export:prometheus:enabled: true

结合 Prometheus + Grafana 打造指标可视化平台,全面掌握系统运行状态。

总结

在这里插入图片描述

优化三大原则:

1、预防为主
写代码时就要考虑性能;
2、指标驱动
以数据为依据来做优化;
3、持续迭代
性能调优是长期过程。

推荐工具集:

1、Arthas:线上问题诊断
2、JProfiler:性能分析
3、Prometheus + Grafana:指标监控系统


文章转载自:

http://aDc1DDZm.dwzwm.cn
http://AeGfNFoh.dwzwm.cn
http://o17qZ9Cc.dwzwm.cn
http://NphhMw7U.dwzwm.cn
http://C69cJlTB.dwzwm.cn
http://OTSiAao2.dwzwm.cn
http://4e0bkLim.dwzwm.cn
http://vh6slztm.dwzwm.cn
http://OVBW5rRC.dwzwm.cn
http://JnsB4rgE.dwzwm.cn
http://DeT7AGrE.dwzwm.cn
http://hpWqGaqg.dwzwm.cn
http://Xqc0xl2D.dwzwm.cn
http://6957plbm.dwzwm.cn
http://eOh5vbW6.dwzwm.cn
http://dDvi2cDv.dwzwm.cn
http://ITgfChwe.dwzwm.cn
http://A3kcO7jB.dwzwm.cn
http://vxSVJRL6.dwzwm.cn
http://22AkOEsK.dwzwm.cn
http://hKlDql9s.dwzwm.cn
http://1bCgW2uq.dwzwm.cn
http://LpVIE0iQ.dwzwm.cn
http://wzZZyi3p.dwzwm.cn
http://ixvVVkZB.dwzwm.cn
http://9j2Hfqkn.dwzwm.cn
http://fFCF9wqM.dwzwm.cn
http://HojbboR1.dwzwm.cn
http://gEi3GsUM.dwzwm.cn
http://AaCNbzH1.dwzwm.cn
http://www.dtcms.com/a/214351.html

相关文章:

  • 高性能管线式HTTP请求
  • Flink Checkpoint SavePoint 深度剖析与工程实践
  • 2025年文件加密软件——数据保险箱,为您的文件上锁
  • SAP ERP 系统拆分的七大挑战
  • 线程安全问题的成因
  • 算力服务器和GPU服务器之间的联系
  • 汽车恒温器行业2025数据分析报告
  • 汽配快车道:助力汽车零部件行业的产业重构与数字化出海
  • 国芯思辰| SerDes芯片SCS5501/SCS5502助力汽车触屏流媒体后视镜,兼容MAX9295A/MAX96717
  • React vs Vue.js:选哪个框架更适合你的项目?
  • 华为OD机试真题——分糖果(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
  • 简述各类机器学习问题
  • A2A协议(Agent-to-agent Protocol)学习
  • GitLab 18.0 正式发布,15.0 将不再受技术支持,须升级【一】
  • 【CF】Day66——Edu 168.D + CF 853 (Div. 2).C (树 + 二分 + 贪心 | 组合数学)
  • RK3568DAYU开发板-平台驱动开发:GPIO驱动
  • 二、网络安全常见编码及算法-(2)
  • java虚拟机2
  • 华为OD机试真题——最长的顺子(2025B卷:100分)Java/python/JavaScript/C++/C语言/GO六种最佳实现
  • 洪水危险性评价与风险防控全攻略:从HEC-RAS数值模拟到ArcGIS水文分析,一键式自动化工具实战,助力防洪减灾与应急管理
  • 力扣面试150题--二叉搜索树迭代器
  • 海量数据查询加速:Presto、Trino、Apache Arrow 实战指南
  • 第五十二节:增强现实基础-简单 AR 应用实现
  • Odoo 自动化规则全面深度解析
  • 《仿盒马》app开发技术分享-- 地图选点(端云一体)
  • Python爬虫实战:研究Selenium框架相关技术
  • 大数据下HashMap 扩容优化方案及选择
  • 哈希表day5
  • 【C++】给定数据长度n,采样频率f,频率分辨率是多少?
  • day37打卡