當你使用myisam引擎時,不得不注意query cache,如果應用上對錶頻繁的修改和查詢,那麼query cache會導致開銷非常的大,所以什麼時候用query cache、怎麼去優化query cache,我們從兩個方面來分析
一、應用上分析
你的數據庫是否採用的讀寫分離,是否對某些表的修改比較頻繁,如果採用了讀寫分離,那麼儘量在master上把query cache關閉,如果對某些表的修改比較頻繁,那麼就可以在查詢這個表的語句上加上sql_no_cache關鍵字。
二、數據庫狀態分析
mysql>show status like "Com_%";
| Com_admin_commands | 18412894 |
| Com_alter_table | 2 |
| Com_change_db | 11954 |
| Com_delete | 3438648 |
| Com_flush | 36 |
| Com_grant | 45 |
| Com_insert | 26241207 |
| Com_insert_select | 245 |
| Com_lock_tables | 1 |
| Com_optimize | 1 |
| Com_preload_keys | 3 |
| Com_select | 130432714 |
| Com_set_option | 301213088 |
| Com_show_charsets | 28 |
| Com_show_collations | 42 |
| Com_show_create_table | 6726 |
| Com_show_databases | 1 |
| Com_show_processlist | 20 |
| Com_show_slave_hosts | 170 |
| Com_show_status | 203 |
| Com_show_storage_engines | 27 |
| Com_show_triggers | 1 |
| Com_show_variables | 12073 |
| Com_unlock_tables | 1 |
| Com_update | 32765432 |
mysql>show status like "Qcache%";
| Qcache_free_blocks | 57780 |
| Qcache_free_memory | 206261152 |
| Qcache_hits | 38673416 |
| Qcache_inserts | 127206895 |
| Qcache_lowmem_prunes | 142543 |
| Qcache_not_cached | 6780160 |
| Qcache_queries_in_cache | 101738 |
| Qcache_total_blocks | 261373 |
- Qcache_free_blocks:目前還處於空閒狀態的 Query Cache 中內存 Block 數目
- Qcache_free_memory:目前還處於空閒狀態的 Query Cache 內存總量
- Qcache_hits:Query Cache 命中次數
- Qcache_inserts:向 Query Cache 中插入新的 Query Cache 的次數,也就是沒有命中的次數,大致等於Com_select
- Qcache_lowmem_prunes:當 Query Cache 內存容量不夠,需要從中刪除老的 Query Cache 以給新的 Cache 對象使用的次數
- Qcache_not_cached:沒有被 Cache 的 SQL 數,包括無法被 Cache 的 SQL 以及由於 query_cache_type 設置的不會被 Cache 的 SQL
- Qcache_queries_in_cache:目前在 Query Cache 中的 SQL 數量
- Qcache_total_blocks:Query Cache 中總的 Block 數量
根據計算緩存命中率爲30%,由於這些數據都是在master上取出來的,所有的查詢都是針對某一個表進行的,而那個表修改的也比較多。只要修改一條數據,也就是表被變更了, 那麼整個表的緩存集都會失效,所以由此來看,這個並不適合開query_cache。如果某些表修改比較少,某些表修改比較多,那麼可以針對修改比較多的那個表的查詢語句加上sql_no_cache關鍵字