查詢緩存將 SELECT 結果集完整緩存,相同查詢直接返回結果,繞過解析、優化、執行全流程。實測:開啟前 CPU 120% → 開啟後 10%,效果顯著。
mysql> SHOW VARIABLES LIKE '%query_cache%';
+------------------------------+----------+
| Variable_name | Value |
+------------------------------+----------+
| have_query_cache | YES |
| query_cache_limit | 1048576 |
| query_cache_min_res_unit | 4096 |
| query_cache_size | 20971520 |
| query_cache_type | ON |
| query_cache_wlock_invalidate | OFF |
+------------------------------+----------+
query_cache_type = ON 表示已啟用。若為 OFF 需配置開啟。
# /etc/my.cnf
[mysqld]
query_cache_size = 20M
query_cache_type = ON
重啟生效:service mysql restart
mysql> SHOW STATUS LIKE 'qcache%';
+-------------------------+----------+
| Variable_name | Value |
+-------------------------+----------+
| Qcache_free_blocks | 83 |
| Qcache_free_memory | 19811040 |
| Qcache_hits | 3108196 |
| Qcache_inserts | 757254 |
| Qcache_lowmem_prunes | 20720 |
| Qcache_not_cached | 47219 |
| Qcache_queries_in_cache | 47 |
| Qcache_total_blocks | 276 |
+-------------------------+----------+
| 指標 | 含義 | 健康判斷 |
|---|---|---|
Qcache_hits | 命中次數 | 越高越好 |
Qcache_inserts | 插入次數(未命中) | 對比 Hits 計算命中率 |
Qcache_hits / (Qcache_hits + Qcache_inserts) | 命中率 | > 80% 為優秀 |
Qcache_lowmem_prunes | 因內存不足清理次數 | 持續增長 = 緩存太小或碎片嚴重 |
Qcache_free_blocks | 空閒塊數(碎片指標) | 過大執行 FLUSH QUERY CACHE 整理 |
Qcache_not_cached | 不緩存查詢數 | 含非 SELECT、不確定函數(NOW())、大結果集 |
命中率 = 3108196 / (3108196 + 757254) = 80.4% -- 良好
| 參數 | 建議值 | 說明 |
|---|---|---|
query_cache_size | 50M-200M | 視機器內存與查詢結果集大小,避免過大鎖競爭 |
query_cache_limit | 1M-4M | 單個結果集超過此值不緩存,防大查詢佔滿緩存 |
query_cache_min_res_unit | 4K-8K | 分配最小單元,過小碎片多,過大浪費內存 |
query_cache_wlock_invalidate | ON | 寫鎖時使相關緩存失效,保證數據一致性 |
SELECT SQL_NO_CACHE COUNT(*) FROM users WHERE email = 'hello';
適用於:實時性要求高、頻繁更新的表、大結果集查詢。
MySQL 5.7.20 起標記棄用,8.0 完全移除 Query Cache。
query_cache_* 配置,否則啟動報錯