啟用MySQL查詢緩存能夠極大地減低數據庫server的CPU使用率,實際使用情況是:開啟前CPU使用率120%左右,開啟后降到了10%。
查看查詢緩存情況:
mysql> show variables like '%query_cache%';
(query_cache_type 為 ON 表示已經開啟)
+------------------------------+----------+
| 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 |
+------------------------------+----------+
假設不是ON,改動配置文件以開啟查詢緩存:
> vi /etc/my.cnf
[mysqld]中加入:
query_cache_size = 20M
query_cache_type = ON
重新啟動mysql服務:
> 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_free_blocks:緩存中相鄰內存塊的個數。
數目大說明可能有碎片。FLUSH QUERY CACHE會對緩存中的碎片進行整理,從而得到一個空暇塊。
- Qcache_free_memory:緩存中的空暇內存。
- Qcache_hits:每次查詢在緩存中命中時就增大
- Qcache_inserts:每次插入一個查詢時就增大。命中次數除以插入次數就是不中比率。
- Qcache_lowmem_prunes:緩存出現內存不足而且必需要進行清理以便為很多其它查詢提供空間的次數。
這個數字最好長時間來看;假設這個 數字在不斷增長。就表示可能碎片非常嚴重。或者內存非常少。(上面的 free_blocks和free_memory能夠告訴您屬於哪種情況)
- Qcache_not_cached:不適合進行緩存的查詢的數量。一般是因為這些查詢不是 SELECT 語句或者用了now()之類的函數。
- Qcache_queries_in_cache:當前緩存的查詢(和響應)的數量。
- Qcache_total_blocks:緩存中塊的數量。
對於某些不想使用緩存的語句。能夠這樣使用:
select
SQL_NO_CACHE count(*) from users where email = 'hello';
(
原創文章。轉載請注明轉自Clement-Xu的csdn博客。)