數據庫連接池調優:精準匹配系統資源
癥狀:
默認配置下,連接池資源使用不當,高并發時連接耗盡或排隊。
常見誤區:
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:指標監控系統