天天看点

关于 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:缓存中块的数量。