近期发现管理的一些MySQL实例偶发会出现连接数飙高,响应时间增长,负载上升等问题,但是业务又没有任何的波动,经过一定的排查发现是query cache lock导致。
问题表现:
419 State: Waiting for query cache lock
4 State: statistics
2 State: storing result in query cache
2 State: Sending data
1 State: Waiting for master to send event
关闭query cache 后:
1067 State:
1 State: Waiting for master to send event
1 State: Slave has read all relay log; waiting for the slave I/O thread to update it
关闭的效果非常明显,于是研究了一下query cache lock的问题。
首先,如果开启query cache,mysql再执行一个query的时候会先锁住query cache,然后判断是否再query cache中存在,如果存在直接返回结果,如果不存在,则再进行引擎查询等操作
mysql> show profile for query 4;
+--------------------------------+----------+
| Status | Duration |
+--------------------------------+----------+
| starting | 0.000015 |
| Waiting for query cache lock | 0.000003 |
| checking query cache for query | 0.000045 |
| checking permissions | 0.000006 |
| Opening tables | 0.000027 |
| System lock | 0.000007 |
| Waiting for query cache lock | 0.000032 |
| init | 0.000018 |
| optimizing | 0.000008 |
| statistics | 0.033109 |
| preparing | 0.000019 |
| executing | 0.000002 |
| Sending data | 4.575480 |
| Waiting for query cache lock | 0.000005 |
| Sending data | 5.527728 |
| Waiting for query cache lock | 0.000005 |
| Sending data | 5.743041 |
| Waiting for query cache lock | 0.000004 |
| Sending data | 6.191706 |
| end | 0.000007 |
| query end | 0.000005 |
| closing tables | 0.000028 |
| freeing items | 0.000008 |
| Waiting for query cache lock | 0.000002 |
| freeing items | 0.000182 |
| Waiting for query cache lock | 0.000002 |
| freeing items | 0.000002 |
| storing result in query cache | 0.000004 |
| logging slow query | 0.000001 |
| logging slow query | 0.000002 |
| cleaning up | 0.000003 |
+--------------------------------+----------+
其次,我们知道,所有insert、update和delete操作都会清空query cahce中被影响表的缓存,从而重新开始种cache。
The query cache always contains current and reliable data. Any insert, update, delete, or other modification to a table causes any relevant entries in the query cache to be flushed.
那么问题就来了,当我们的数据库不是那么频繁的更新的时候,query cache是个好东西,可以在本地形成一个cache,提高RT响应时间,但是如果反过来,如果写入非常频繁,并集中在某机张表上的时候。
那么query cache lock的锁机制会造成很频繁的锁冲突,对于这一张表的写和读会互相等待query cache lock解锁,导致select的查询效率下降。
相关阅读: