清除MySQL缓存

11 浏览
0 Comments

清除MySQL缓存

我接手了一个使用Laravel 4编写的项目。我们使用的是MySQL 5.6.21 - PHP 5.4.30,并且目前运行在Windows 8.1上。

每天早上第一次访问包含约5个后端查询的首页时,该网站会因为php超时(超过30秒无响应)而崩溃。

我通过使用以下方法逐渐接近问题的原因:Laravel 4 - logging SQL queries。其中一个查询在第一次调用时耗时超过25秒,之后始终在<0.5秒内完成。

该查询有3个连接和2个子查询,包裹在Cache::remember中。我希望对其进行优化,以便在生产环境中不会遇到这个问题。

所以我想测试不同的SQL语句

问题是第一次数据被缓存了,我无法看到我的新SQL是否更好。

现在,由于我猜测这是一个缓存问题(第一次尝试时耗时长,之后不再),我尝试了以下操作:

MySQL: FLUSH TABLES;
重启MySQL
重启Apache
php artisan cache:clear

但是,查询仍然很快。然后经过一段时间不再访问数据库(无法给出确切的时间,可能是4小时的非活动时间)后,问题再次发生。

Explain的结果如下:

1 | Primary | table1 | ALL | 2 possible keys | NULL | ... | 1010000 | using where; using temporary; using filesort
1 | Primary | table2 | eq_ref | PRIMARY | PRIMARY | ... | 1 | using where; using index
1 | Primary | table3 | eq_ref | PRIMARY | PRIMARY | ... | 1 | using where; using index
1 | Primary | table4 | eq_ref | PRIMARY | PRIMARY | ... | 1 | NULL
3 | Dependent Subquery | table5 | ref | 2 possible keys | table1.id | ... | 17 | using where
2 | Dependent Subquery | table5 | ref | 2 possible keys | table1.id | ... | 17 | using where

所以这里有几个问题:

  • 为什么会出现这么长的时间?
  • 我如何重现这个问题?
  • 是否有方法可以修复它?

我阅读了mysql slow on first query, then fast for related queries。然而,这并没有回答我的问题,即如何重现这种行为。


更新

我更改了SQL语句,现在它的写法是这样的:

select 
    count(ec.id) as asdasda
from table1 ec force index for join (PRIMARY)
    left join table2 e force index for join (PRIMARY) on ec.id = e.id
    left join table3 v force index for join (PRIMARY) on e.id = v.id 
where
    v.col1 = 'aaa'
    and v.col2 = 'bbb'
    and v.col3 = 'ccc'
    and e.datecol > curdate()
    and e.col1 != 0

现在Explain的结果如下:

+----+-------------+--------+--------+---------------+--------------+---------+-----------------+--------+-------------+
| id | select_type | table  | type   | possible_keys | key          | key_len | ref             | rows   | Extra       |
+----+-------------+--------+--------+---------------+--------------+---------+-----------------+--------+-------------+
|  1 | SIMPLE      | table3 | ALL    | PRIMARY       | NULL         | NULL    | NULL            | 114032 | Using where |
|  1 | SIMPLE      | table2 | ref    | PRIMARY       | PRIMARY      | 5       | table3.id       |     11 | Using where |
|  1 | SIMPLE      | table1 | eq_ref | PRIMARY       | PRIMARY      | 4       | table2.id       |      1 | Using index |
+----+-------------+--------+--------+---------------+--------------+---------+-----------------+--------+-------------+

这是最好的结果了吗?

0
0 Comments

MySQL缓存清除问题的原因是数据可能被缓存在InnoDB缓冲池或Windows文件系统缓存中。解决方法是通过设置刷新参数为更积极的值来清除InnoDB缓存。对于Windows文件系统缓存,可以使用提供的解决方案来清除。此外,确保在重新启动MySQL时不要忘记缓冲池。如果你在Windows上,也可以尝试清除文件系统缓存。

0