---
title: "mysql查询缓存"
author: "zhb8015"
date: "2015-08-05T15:22:49Z"
tags: []
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2015-08-05T15:26:00Z"
id: 2233018
url: "https://peter8015.iteye.com/blog/2233018"
---

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服务器即可。 

Java代码  [![收藏代码](http://orangeholic.iteye.com/images/icon_star.png)]()

1. query\_cache\_size=10M
2. 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结果还是等写操作完成再读表获取结果。 

Java代码  [![收藏代码](http://orangeholic.iteye.com/images/icon_star.png)]()

01. mysql&gt; show variables like '%query\_cache%';
02. +------------------------------+----------+
03. | Variable\_name                | Value    |
04. +------------------------------+----------+
05. | have\_query\_cache             | YES      |
06. | query\_cache\_limit            | 1048576  |
07. | query\_cache\_min\_res\_unit     | 4096     |
08. | query\_cache\_size             | 10485760 |
09. | query\_cache\_type             | ON       |
10. | query\_cache\_wlock\_invalidate | OFF      |
11. +------------------------------+----------+
12. 6 rows in set (0.00 sec)

2.测试   
我们先执行一次，select  count(\*) from wei ;然后再执行一次，可以看出第二次用的时间远远低于第一次的执行，因为第二次从缓存中读取了select结果。 

Java代码  [![收藏代码](http://orangeholic.iteye.com/images/icon_star.png)]()

01. mysql&gt; select  count(\*) from wei ;
02. +----------+
03. | count(\*) |
04. +----------+
05. |  4194304 |
06. +----------+
07. 1 row in set (3.92 sec)
08. mysql&gt; select  count(\*) from wei ;
09. +----------+
10. | count(\*) |
11. +----------+
12. |  4194304 |
13. +----------+
14. 1 row in set (0.00 sec)

我们可以通过如下命令查看现在缓存的情况 

Java代码  [![收藏代码](http://orangeholic.iteye.com/images/icon_star.png)]()

01. mysql&gt; show status like 'qcache%';
02. +-------------------------+----------+
03. | Variable\_name           | Value    |
04. +-------------------------+----------+
05. | Qcache\_free\_blocks      | 1        |
06. | Qcache\_free\_memory      | 10475424 |
07. | Qcache\_hits             | 1        |
08. | Qcache\_inserts          | 1        |
09. | Qcache\_lowmem\_prunes    | 0        |
10. | Qcache\_not\_cached       | 0        |
11. | Qcache\_queries\_in\_cache | 1        |
12. | Qcache\_total\_blocks     | 4        |
13. +-------------------------+----------+
14. 8 rows in set (0.00 sec)

其中各个参数的意义如下：   
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：缓存中块的数量。

 

mysql 开启查询缓存可以有两种方法来开启一种是使用set命令来进行开启，另一种是直接修改my.ini文件来直接设置都是非常的简单的哦。

&lt;iframe id="aswift\_0" style="left: 0px; position: absolute; top: 0px;" name="aswift\_0" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="300" height="250"&gt;&lt;/iframe&gt;

&lt;iframe id="cproIframe\_u1339684\_1" src="http://pos.baidu.com/acom?adn=3&amp;at=134&amp;aurl=&amp;cad=1&amp;ccd=24&amp;cec=GBK&amp;cfv=18&amp;ch=0&amp;col=zh-CN&amp;conOP=0&amp;cpa=1&amp;dai=1&amp;dis=0&amp;layout\_filter=rank%2Ctabcloud&amp;ltr=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DVO3uBrVvqviOfus93PbDYXXOhG3\_gztRKcGWXorhtvYQKUe3mZN-J-kNNPrN5b5yEyrBh4OeqxZhB6-Mcg0CWa%26wd%3D%26eqid%3Dcaa45ed400007b250000000355c1ba44&amp;ltu=http%3A%2F%2Fwww.111cn.net%2Fdatabase%2Fmysql%2F63815.htm&amp;lunum=6&amp;n=mailangel123\_cpr&amp;pcs=1349x677&amp;pis=10000x10000&amp;ps=434x525&amp;psr=1366x768&amp;pss=1349x725&amp;qn=573287b0d6c25b2a&amp;rad=&amp;rsi0=300&amp;rsi1=250&amp;rsi5=4&amp;rss0=%23FFFFFF&amp;rss1=%23FFFFFF&amp;rss2=%230000FF&amp;rss3=%23444444&amp;rss4=%23008000&amp;rss5=&amp;rss6=%23e10900&amp;rss7=&amp;scale=&amp;skin=&amp;td\_id=1339684&amp;tn=text\_default\_300\_250&amp;tpr=1438759491024&amp;ts=1&amp;version=2.0&amp;xuanting=0&amp;dtm=BAIDU\_DUP2\_SETJSONADSLOT&amp;dc=2&amp;di=u1339684&amp;ti=mysql%20%E5%BC%80%E5%90%AF%E6%9F%A5%E8%AF%A2%E7%BC%93%E5%AD%98%E6%96%B9%E6%B3%95%E4%B8%8E%E6%9F%A5%E8%AF%A2%E4%BE%8B%E5%AD%90-mysql%E6%95%99%E7%A8%8B-%E6%95%B0%E6%8D%AE%E5%BA%93-%E5%A3%B9%E8%81%9A%E6%95%99%E7%A8%8B%E7%BD%91&amp;tt=1438759491005.21.149.154" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" align="center,center" width="300" height="250"&gt;&lt;/iframe&gt;

开启缓存，设置缓存大小，具体实施如下：

**1、修改配置文件,windows下是my.ini，[linux](http://www.111cn.net/list-156/)下是my.cnf;**

在配置文件的最后追加上：

 代码如下 复制代码

query\_cache\_type = 1  
query\_cache\_size = 600000

需要重启mysql生效；

**那么采用第二种方式；**

b) 开启缓存,两种方式：

a)使用mysql命令：

 代码如下 复制代码

set global query\_cache\_type = 1;    
set global query\_cache\_size = 600000;

如果报错：

query cache is disabled; restart the server with query\_cache\_type=1...

**在mysql命令行输入**

show variables like "%query\_cache%" 查看是否设置成功，现在可以使用缓存了；  
当然如果你的数据表有更新怎么办，没关系mysql默认会和这个表有关系的缓存删掉，下次查询的时候会直接读表然后再缓存

**下面是一个简单的例子：**

 代码如下 复制代码

\[MySQL@csdba1850 ~]$ MySQL -u root -p  
Enter pass[word](http://www.111cn.net/list-189/):  
Welcome to the MySQL monitor. Commands end with ; or /g.  
Your MySQL connection id is 3  
Server version: 5.0.45-community MySQL Community Edition (GPL)  
Type 'help;' or '/h' for help. Type '/c' to clear the buffer.  
MySQL&gt; set global query\_cache\_size = 600000;

设置缓存内存

Query OK, 0 rows affected (0.00 sec)  
MySQL&gt; set session query\_cache\_type = ON;

开启查询缓存

Query OK, 0 rows affected (0.00 sec)  
MySQL&gt; use test Reading table information for completion   
of table and column names You can turn off this feature to   
get a quicker startup with -A Database changed mysql&gt; show tables;   
+----------------+ | Tables\_in\_test | +----------------+ | animals |   
| person | +----------------+ 5 rows in set (0.00 sec)   
mysql&gt; [select](http://www.111cn.net/tags.php/select/) count(\*) from animals; +----------+ | count(\*)   
| +----------+ | 6 | +----------+ 1 row in set (0.00 sec)

Qcache\_hits表示mysql缓存查询在缓存中命中的累计次数，是累加值。

mysql&gt; SHOW STATUS LIKE 'Qcache\_hits'; +---------------+-------+   
| Variable\_name | Value | +---------------+-------+ | Qcache\_hits   
| 0 | --0次 +---------------+-------+ 8 rows in set (0.00 sec)   
mysql&gt; select count(\*) from animals; +----------+ | count(\*)   
| +----------+ | 6 | +----------+ 1 row in set (0.00 sec)   
mysql&gt; SHOW STATUS LIKE 'Qcache%'; +---------------+-------+   
| Variable\_name | Value | +---------------+-------+ | Qcache\_hits | 1 | 

表示sql在缓存中直接得到结果，不需要再去解析

+---------------+-------+ 8 rows in set (0.00 sec)   
mysql&gt; select count(\*) from animals; +----------+   
| count(\*) | +----------+ | 6 | +----------+ 1 row in set (0.00 sec)   
mysql&gt; select count(\*) from animals; +----------+ | count(\*)   
| +----------+ | 6 | +----------+ 1 row in set (0.00 sec)   
mysql&gt; SHOW STATUS LIKE 'Qcache\_hits'; +---------------+-------+   
| Variable\_name | Value | +---------------+-------+ | Qcache\_hits | 3 | 

上面的sql也是是从缓存中直接取到结果

+---------------+-------+ 1 row in set (0.00 sec) mysql&gt; insert into animals select 9,'testsds' ; 

插入数据后，跟这个表所有相关的sql缓存就会被清空掉

Query OK, 1 row affected (0.00 sec) Records:   
1 Duplicates: 0 Warnings: 0 mysql&gt; select count(\*) from animals;   
+----------+ | count(\*) | +----------+ | 7 | +----------+   
1 row in set (0.00 sec) mysql&gt; SHOW STATUS LIKE 'Qcache\_hits';   
+---------------+-------+ | Variable\_name | Value |   
+---------------+-------+ | Qcache\_hits | 3 | 

还是等于3，说明上一条sql是没有直接从缓存中直接得到的

+---------------+-------+ 1 row in set (0.00 sec)   
mysql&gt; select count(\*) from animals; +----------+   
| count(\*) | +----------+ | 7 | +----------+   
1 row in set (0.00 sec) mysql&gt; SHOW STATUS LIKE 'Qcache\_hits';   
+---------------+-------+ | Variable\_name | Value | +---------------+-------+   
| Qcache\_hits | 4 | +---------------+-------+ 1 row in set (0.00 sec) 

以上的相关内容就是对mysql缓存查询和设置的介绍，望你能有所收获。

**补充**

**第一： query\_cache\_type 使用查询缓存的方式**  
一般，我们会把 query\_cache\_type 设置为 ON,默认情况下应该是ON

 代码如下 复制代码 mysql&gt; select @@query\_cache\_type;  
+--------------------+  
| @@query\_cache\_type |  
+--------------------+  
| ON |  
+--------------------+

query\_cache\_type有3个值 0代表关闭查询缓存OFF，1代表开启ON，2（DEMAND）代表当sql语句中有SQL\_CACHE关键词时才缓存，如：select SQL\_CACHE user\_name from users where user\_id = '100';  
这样 当我们执行 select id,name from tableName; 这样就会用到查询缓存。  
①在 query\_cache\_type 打开的情况下，如果你不想使用缓存，需要指明  
select sql\_no\_cache id,name from tableName;  
②当sql中用到mysql函数，也不会缓存  
   
当然也可以禁用查询缓存： mysql&gt; set session query\_cache\_type=off;  
第二： 系统变量 have\_query\_cache 设置查询缓存是否可用

 代码如下 复制代码 mysql&gt; show variables like 'have\_query\_cache';  
+------------------+-------+  
| Variable\_name | Value |  
+------------------+-------+  
| have\_query\_cache | YES |

+------------------+-------+  
上面的显示，表示设置查询缓存是可用的。  
第三： 系统变量 query\_cache\_size  
表示查询缓存大小，也就是分配内存大小给查询缓存，如果你分配大小为0，  
那么 第一步 和 第二步 起不到作用，还是没有任何效果。

 代码如下 复制代码 mysql&gt; select @@global.query\_cache\_size;  
+---------------------------+  
| @@global.query\_cache\_size |  
+---------------------------+  
| 16777216 |  
+---------------------------+

上面是 mysql6.0设置默认的，之前的版本好像默认是0的，那么就要自己设置下。  
设置 set @@global.query\_cache\_size=1000000; 这里是设置1M左右，900多K。  
再次查看下

 代码如下 复制代码 select @@global.query\_cache\_size;  
+---------------------------+  
| @@global.query\_cache\_size |  
+---------------------------+  
| 999424 |  
+---------------------------+

显示我们设置新的大小，表示设置成功。  
第四： query\_cache\_limit 控制缓存查询结果的最大值  
例如： 如果查询结果很大， 也缓存？？？？这个明显是不可能的。  
MySql 可以设置一个最大的缓存值，当你查询缓存数结果数据超过这个值就不会  
进行缓存。缺省为1M，也就是超过了1M查询结果就不会缓存。

 代码如下 复制代码 mysql&gt; select @@global.query\_cache\_limit;  
+----------------------------+  
| @@global.query\_cache\_limit |  
+----------------------------+  
| 1048576 |  
+----------------------------+

这个是默认的数值，如果需要修改，就像设置缓存大小一样设置，使用set  
重新指定大小。  
好了，通过4个步骤就可以 打开了查询缓存，具体值的大小和查询的方式 这个因不同  
的情况来指定了。  
mysql查询缓存相关变量

 代码如下 复制代码 mysql&gt; 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             | 16777216 |  
| query\_cache\_type             | ON       |  
| query\_cache\_wlock\_invalidate | OFF      |  
+------------------------------+----------+  
6 rows in set (0.00 sec)

第五：查看缓存的状态

 代码如下 复制代码 mysql&gt; show status like '%Qcache%';  
+-------------------------+----------+  
| Variable\_name           | Value    |  
+-------------------------+----------+  
| Qcache\_free\_blocks      | 11       |  
| Qcache\_free\_memory      | 16610552 |  
| Qcache\_hits             | 10       |  
| Qcache\_inserts          | 155      |  
| Qcache\_lowmem\_prunes    | 0        |  
| Qcache\_not\_cached       | 21       |  
| Qcache\_queries\_in\_cache | 111      |  
| Qcache\_total\_blocks     | 256      |  
+-------------------------+----------+  
8 rows in set (0.00 sec)

MySQL 提供了一系列的 Global Status 来记录 Query Cache 的当前状态，具体如下：  
Qcache\_free\_blocks：目前还处于空闲状态的 Query Cache 中内存 Block 数目  
Qcache\_free\_memory：目前还处于空闲状态的 Query Cache 内存总量  
Qcache\_hits：Query Cache 命中次数  
Qcache\_inserts：向 Query Cache 中插入新的 Query Cache 的次数，也就是没有命中的次数  
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 数量  
   
第六：检查查询缓存使用情况  
检查是否从查询缓存中受益的最简单的办法就是检查缓存命中率  
当服务器收到SELECT 语句的时候，Qcache\_hits 和Com\_select 这两个变量会根据查询缓存  
的情况进行递增  
查询缓存命中率的计算公式是：Qcache\_hits/(Qcache\_hits + Com\_select)。

 代码如下 复制代码 mysql&gt; show status like '%Com\_select%';  
+---------------+-------+  
| Variable\_name | Value |  
+---------------+-------+  
| Com\_select    | 1     |  
+---------------+-------+

   
   
query\_cache\_min\_res\_unit的配置是一柄”双刃剑”，默认是4KB，设置值大对大数据查询有好处，但如果你的查询都是小数据 查询，就容易造成内存碎片和浪费。

查询缓存碎片率 = Qcache\_free\_blocks / Qcache\_total\_blocks * 100%

如果查询缓存碎片率超过20%，可以用FLUSH QUERY CACHE整理缓存碎片，或者试试减小query\_cache\_min\_res\_unit，如果你的查询都是小数据量的话。

查询缓存利用率 = (query\_cache\_size - Qcache\_free\_memory) / query\_cache\_size * 100%

查询缓存利用率在25%以下的话说明query\_cache\_size设置的过大，可适当减小;查询缓存利用率在80%以上而且 Qcache\_lowmem\_prunes &gt; 50的话说明query\_cache\_size可能有点小，要不就是碎片太多。

查询缓存命中率 = (Qcache\_hits - Qcache\_inserts) / Qcache\_hits * 100%

示例服务器 查询缓存碎片率 = 20.46%，查询缓存利用率 = 62.26%，查询缓存命中率 = 1.94%，命中率很差，可能写操作比较频繁吧，而且可能有些碎片。