---
title: "Mysql Query Cache学习篇"
author: "libin123"
date: "2012-03-19T14:32:24Z"
tags: []
categories: ["数据库"]
slug: "mysql-query-cache"
draft: false
lastmod: "2012-03-19T14:22:13Z"
id: 1457536
url: "https://dbua.iteye.com/blog/1457536"
---

**基础介绍篇：**

QueryCache是用来缓存select语句结果集的一种机制，不是缓存execution plan。需要注意：对select语句的大小写空格敏感。

用张形象的图可以展现下(图是从网上“借”的)：

[![](http://qa.taobao.com/wp-content/uploads/2010/10/1-300x188.png)](http://qa.taobao.com/wp-content/uploads/2010/10/1.png)

无实验，无真像，我们还是动手理解下吧

先看下当前环境状态

> mysql&gt; select version();  
> +————–+  
> | version()    |  
> +————–+  
> | 5.1.45-debug |  
> +————–+  
> 1 row in set (0.00 sec)
> 
> mysql&gt; show status like ‘%qcache%’;  
> +————————-+———-+  
> | Variable\_name           | Value    |  
> +————————-+———-+  
> | Qcache\_free\_blocks      | 1        |  
> | Qcache\_free\_memory      | 67099584 |  
> | Qcache\_hits             | 0        |  
> | Qcache\_inserts          | 0        |  
> | Qcache\_lowmem\_prunes    | 0        |  
> | Qcache\_not\_cached       | 2        |  
> | Qcache\_queries\_in\_cache | 0        |  
> | Qcache\_total\_blocks     | 1        |  
> +————————-+———-+  
> 8 rows in set (0.00 sec)

看看Query Cache的参数设置，已经打开query cache了(ON)

> mysql&gt; show variables like ‘%query\_cache%’;  
> +——————————+———-+  
> | Variable\_name                | Value    |  
> +——————————+———-+  
> | have\_query\_cache             | YES      |  
> | query\_cache\_limit            | 1048576  |  
> | query\_cache\_min\_res\_unit     | 2048     |  
> | query\_cache\_size             | 67108864 |  
> | query\_cache\_type             | ON       |  
> | query\_cache\_wlock\_invalidate | OFF      |  
> +——————————+———-+  
> 6 rows in set (0.00 sec)

这是一个有一百万行记录的测试表：

> mysql&gt; select count(distinct(pad)) from sbtest;  
> +———————-+  
> | count(distinct(pad)) |  
> +———————-+  
> |                    1 |  
> +———————-+  
> 1 row in set (4.57 sec)

> 再看下状态，由于是第一次执行本select语句，自然没在cache中，所以是insert进去没hit到：  
> mysql&gt; show status like ‘%qcache%’;  
> +————————-+———-+  
> | Variable\_name           | Value    |  
> +————————-+———-+  
> | Qcache\_free\_blocks      | 1        |  
> | Qcache\_free\_memory      | 67098048 |  
> | Qcache\_hits             | 0        |  
> | Qcache\_inserts          | 1        |  
> | Qcache\_lowmem\_prunes    | 0        |  
> | Qcache\_not\_cached       | 2        |  
> | Qcache\_queries\_in\_cache | 1        |  
> | Qcache\_total\_blocks     | 4        |  
> +————————-+———-+  
> 8 rows in set (0.00 sec)

> 再执行一下同样的语句看看效果，执行时间真快呀  
> mysql&gt; select count(distinct(pad)) from sbtest;  
> +———————-+  
> | count(distinct(pad)) |  
> +———————-+  
> |                    1 |  
> +———————-+  
> 1 row in set (0.00 sec)

> 这下子hit到了^-^  
> mysql&gt; show status like ‘%qcache%’;  
> +————————-+———-+  
> | Variable\_name           | Value    |  
> +————————-+———-+  
> | Qcache\_free\_blocks      | 1        |  
> | Qcache\_free\_memory      | 67098048 |  
> | Qcache\_hits             | 1        |  
> | Qcache\_inserts          | 1        |  
> | Qcache\_lowmem\_prunes    | 0        |  
> | Qcache\_not\_cached       | 2        |  
> | Qcache\_queries\_in\_cache | 1        |  
> | Qcache\_total\_blocks     | 4        |  
> +————————-+———-+  
> 8 rows in set (0.00 sec)

> 如果语句大小写不一，还得insert没hit到，呵呵  
> mysql&gt; select COUNT(distinct(pad)) from sbtest;  
> +———————-+  
> | COUNT(distinct(pad)) |  
> +———————-+  
> |                    1 |  
> +———————-+
> 
> 1 row in set (1.99 sec)  
> mysql&gt; show status like ‘%qcache%’;  
> +————————-+———-+  
> | Variable\_name           | Value    |  
> +————————-+———-+  
> | Qcache\_free\_blocks      | 1        |  
> | Qcache\_free\_memory      | 67097024 |  
> | Qcache\_hits             | 1        |  
> | Qcache\_inserts          | 2        |  
> | Qcache\_lowmem\_prunes    | 0        |  
> | Qcache\_not\_cached       | 2        |  
> | Qcache\_queries\_in\_cache | 2        |  
> | Qcache\_total\_blocks     | 6        |  
> +————————-+———-+  
> 8 rows in set (0.00 sec)

如果sbtest表被update/insert/delete等语句操作后，这个select语句的query cache就会被失效。所以如果表被频繁更新，query cache的overhead就会被放大出来。一般的理论是默认打开QC，对一些涉及频繁更新的表的SQL语句可以加上SQL\_NO\_CACHE这样的sql hints来禁用query cache。

顺便提下官方文档里一个有意思的benchmark测试结果数据：

1\. 从表中查出某一条特定记录这样的简单SQL，如果保证每个SQL不同，这样子没利用query cache机制，最终显示query cache的overhead是13%

2\. 如果保证上述那些SQL一样，利用到了query cache机制的话，结果显示会加速238%

**源码学习篇：**

其实涉及的主要的数据结构就是个hash表，key是query + database + flag

这个flag很庞大的其实:

> *struct Query\_cache\_query\_flags*  
> *{*  
> *unsigned int client\_long\_flag:1;*  
> *unsigned int client\_protocol\_41:1;*  
> *unsigned int result\_in\_binary\_protocol:1;*  
> *unsigned int more\_results\_exists:1;*  
> *unsigned int in\_trans:1;*  
> *unsigned int autocommit:1;*  
> *unsigned int pkt\_nr;*  
> *uint character\_set\_client\_num;*  
> *uint character\_set\_results\_num;*  
> *uint collation\_connection\_num;*  
> *ha\_rows limit;*  
> *Time\_zone \*time\_zone;*  
> *ulong sql\_mode;*  
> *ulong max\_sort\_length;*  
> *ulong group\_concat\_max\_len;*  
> *ulong default\_week\_format;*  
> *ulong div\_precision\_increment;*  
> *MY\_LOCALE \*lc\_time\_names;*  
> *};*

一个正常的select QUERY流程很长很长，可以从sql\_parse.cc的dispatch\_command开始看，当执行到里面的mysql\_parse时我们就会看到里面开始涉及query cache了：

> *lex\_start(thd);*  
> *mysql\_reset\_thd\_for\_next\_command(thd);*
> 
> *if (query\_cache\_send\_result\_to\_client(thd, (char\*) inBuf, length) &lt;= 0)*

这个query\_cache\_send\_result\_to\_client很关键，她会判断当前的QUERY能不能从cache中找到结果集，如果符合条件找到的话，就会略过parse\_sql、mysql\_execute\_command也就是说不需要再经过LEX YACC等词语法解析了，也不需要经过语句执行时和存储引擎打交道，避免掉操作系统层和disk之间的IO了。如果找不到，就会解析执行，并且如果结果集小于query\_cache\_limit参数值时会放到cache中（具体详见Query\_cache::store\_query函数）

那个hash查找是这样：

query\_block = (Query\_cache\_block \*)  hash\_search(&queries, (uchar\*) sql,  
tot\_length);  
至于具体的与query\_cache\_min\_res\_unit参数关联很大的cache内存分配策略、update/insert/delete时invalidate cache等等，我们都可以通过单步debug来学习，这里就不一一详述了：）