mysql 优化

Posted by Deadline on November 26, 2015

随着系统逐渐的变大,数据库表也多了,发现加载一些页面很慢,想到要优化下数据库

step1 寻找瓶颈##

mysql 有提供慢查询日志功能,mysql命令行模式运行

show variables like '%quer%';
+-------------------------------+---------------------------------+
| Variable_name                 | Value                           |
+-------------------------------+---------------------------------+
| ft_query_expansion_limit      | 20                              |
| have_query_cache              | YES                             |
| log_queries_not_using_indexes | OFF                             |
| log_slow_queries              | OFF                             |
| long_query_time               | 10.000000                       |
| query_alloc_block_size        | 8192                            |
| query_cache_limit             | 1048576                         |
| query_cache_min_res_unit      | 4096                            |
| query_cache_size              | 0                               |
| query_cache_type              | ON                              |
| query_cache_wlock_invalidate  | OFF                             |
| query_prealloc_size           | 8192                            |
| slow_query_log                | OFF                             |
| slow_query_log_file           | /var/run/mysqld/mysqld-slow.log |
+-------------------------------+---------------------------------+

可以看到 log_slow_queries OFF 慢查询日志处于关闭状态

在 mysql 配置文件中添加下面的配置项,配置文件的目录在 /etc/my.cnf

slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1 #秒为单位,默认为10
log_queries_not_using_indexes = 1 #无索引的查询也记录下来,不建议开启,开了会生成很多条日志

创建文件夹和文件,还要修改文件的属性,其他用户也要有写的权限,防止mysql无法写入文件

mkdir /var/log/mysql
touch /var/log/mysql/slow.log

关于配置参数不同版本可能有些差异

5.1.6版本之前是使用下面的参数

 --log-slow-queries[=file_name] #配置日志文件

具体差异请参考官方文档

配置完成后可以执行

select sleep(2);

如果正确开启了的话,那么在 slow.log 文件中会记录下来,类似下面的记录

# Time: 151126 15:29:17
# User@Host: root[root] @  [116.226.107.209]
# Query_time: 2.000267  Lock_time: 0.000000 Rows_sent: 1  Rows_examined: 0
use mayiangel;
SET timestamp=1448522957;
SELECT SLEEP(2);

具体优化

额,开了一天发现没有记录。 那这部分等后续优化再写吧。


There are no comments on this post.