天天看點

關于 mysql 查詢緩存

查詢緩存的作用就是當查詢接收到一個和之前同樣的查詢,伺服器将會從查詢緩存種檢索結果,而不是再次分析和執行上次的查詢。這樣就大大提高了性能,節省時間。

檢視緩存是否開啟: select @@query_cache_type;

禁用查詢緩存:set session

query_cache_type=off; 這裡的設定隻是對目前的設定,是暫時的

若 執行 set session query_cache_type=off; 時報錯 提示 restart with query_cache_type=1

時 則 編輯配置檔案 my.cnf 添加

[mysqld]

query_cache_size=256M

query_cache_type=1

重新開機 service mysqld restart

/********************************************

query_cache_type有3個值,表示緩存那種類型的select結果集,query_cache_type各個值如下: 

0或off關閉緩存 

1或on開啟緩存,但是不儲存使用sql_no_cache的select語句,如不緩存select 

sql_no_cache name from wei where

id=2 

2或demand開啟有條件緩存,隻緩存帶sql_cache的select語句,緩存select 

sql_cache name from wei where id=4 

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 |

268435456 |

| query_cache_type | ON |

query_cache_wlock_invalidate | OFF

其中have_query_cache為是否開啟,query_cache_limit

指定單個查詢能夠使用的緩沖區大小,預設為1M;query_cache_min_res_unit為系統配置設定的最小緩存塊大小,預設是4KB,設定值大對大資料查詢有好處,但如果你的查詢都是小資料

查詢,就容易造成記憶體碎片和浪費;query_cache_size和query_cache_type就是上面我們的配置;query_cache_wlock_invalidate表示當有其他用戶端正在對MyISAM表進行寫操作時,如果查詢在query

cache中,是否傳回cache結果還是等寫操作完成再讀表擷取結果。

mysql> show status like

‘qcache%‘;

+-------------------------+-----------+

| Variable_name

| Value |

Qcache_free_blocks | 1 |

| Qcache_free_memory | 268417440

| Qcache_hits | 0 |

| Qcache_inserts | 0

| Qcache_lowmem_prunes | 0 |

| Qcache_not_cached |

2 |

| Qcache_queries_in_cache | 0 |

| Qcache_total_blocks

| 1 |

其中各個參數的意義如下: 

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:緩存中塊的數量。