当你使用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关键字