一. 定位sql
1>. 开启mysql慢查询日志
在mysql.cnf
//慢查询日志路径
log-slow-queries = /var/lib/mysql/slow.log
//最长执行时间 s为单位
long_query_time = 2
2>.php-fpm 慢脚本日志
在php-fpm.conf 中
//最长查询时间 s为单位
request_slowlog_timeout = 2
//慢脚本日志路径
slowlog = /aws/server/php/etc/php-fpm.d/slow.log
3>. 框架中 定义慢查询
这里用laravel举例,在 app/Providers/AppServiceProvider.php boot方法中
public function boot()
{
//
DB::listen(function($query){
$sql = $query->sql;
$bingings = $query->bindings;
$time = $query->time;
//time以ms为单位
if($time > 1000) {
Log::debug(compact('sql','bingings','time'));
}
});
}
二. 将定位的慢sql进行优化
这里是一个总结,具体优化在下一篇博客中写
1.explain分析加索引
2.优化sql语句 使用子查询
3. "*"设置为具体字段
其它方案
4.对于命中不高的,建立缓存
5.分库分表,主从库读写分离