MySQL缓存的查询和清除命令使用详解缓存的查询和清除命令使用详解
主要介绍了MySQL缓存的查询和清除命令使用详解,对于一些不常改变数据且有大量相同sql查询的表,查询缓存
会显得比较有用一些,需要的朋友可以参考下
Mysql 查询缓存查询缓存
查询缓存的作用就是当查询接收到一个和之前同样的查询,服务器将会从查询缓存种检索结果,而不是再次分析和执行上次的
查询。这样就大大提高了性能,节省时间。
1.配置查询缓存
修改配置文件,修改[mysqld]下的query_cache_size和query_cache_type(如果没有则添加)。其中query_cache_size表示
缓存的大小,而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服务器即可。
query_cache_size=10M
query_cache_type=1
可以用如下命令查看是否开启,其中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 variables like '%query_cache%';
+------------------------------+----------+
| Variable_name | Value |
+------------------------------+----------+
| have_query_cache | YES |
| query_cache_limit | 1048576 |
| query_cache_min_res_unit | 4096 |
| query_cache_size | 10485760 |
| query_cache_type | ON |
| query_cache_wlock_invalidate | OFF |
+------------------------------+----------+
6 rows in set (0.00 sec)
2.测试
我们先执行一次,select count(*) from wei ;然后再执行一次,可以看出第二次用的时间远远低于第一次的执行,因为第二次
从缓存中读取了select结果。
mysql> select count(*) from wei ;
+----------+
| count(*) |
+----------+
| 4194304 |
+----------+
1 row in set (3.92 sec)
mysql> select count(*) from wei ;
+----------+
| count(*) |
+----------+
| 4194304 |
+----------+
1 row in set (0.00 sec)
我们可以通过如下命令查看现在缓存的情况
mysql> show status like 'qcache%';
+-------------------------+----------+
| Variable_name | Value |
+-------------------------+----------+
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 10475424 |
| Qcache_hits | 1 |
| Qcache_inserts | 1 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached | 0 |
| Qcache_queries_in_cache | 1 |
| Qcache_total_blocks | 4 |
+-------------------------+----------+
8 rows in set (0.00 sec)
评论5