查看查詢緩存情況:
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';