models/posts.php 翻页性能优化
数据量过大时(100w条以上),首页翻页会引起mysql负载过高,原因在于 posts_index 翻页引起的
这里做一个小改造,能有效降低翻页时的负载
修改:models/posts.php 文件
把
$posts_index = $this->fetch_page('posts_index', implode(' AND ', $where), $order_key, $page, $per_page);
$this->posts_list_total = $this->found_rows();
改为 //翻页优化改造
$page = empty($page) ? 1 : $page;
$per_page = empty($per_page) ? 10 : $per_page;
if (empty($category_id)) {
if (!$max_id = AWS_APP::cache()->get('max_post_id') AND empty($where)) {
$max = $this->query_all('SELECT max(`id`) as n FROM ' . get_table('posts_index'));
$max_id = $max[0]['n'];
AWS_APP::cache()->set('max_post_id', $max_id, get_setting('cache_level_high'));
}
$start_id = $max_id - $per_page * $page;
$end_id = $start_id + $per_page;
$where = '`id` BETWEEN ' . $start_id . ' AND ' . $end_id;
//end 翻页改造
$posts_index = $this->fetch_page('posts_index', implode(' AND ', $where), $order_key, 1, $per_page);
$this->posts_list_total = $max_id;
} else {
//分类页不优化
$posts_index = $this->fetch_page('posts_index', implode(' AND ', $where), $order_key, $page, $per_page);
$this->posts_list_total = $this->found_rows();
}虽然这样翻页是不精确的,是根据id估算该页的起止位置,但是能降低翻页的打开时间,可以一试。
分类页没有优化,目前尚未发现其它报错信息!
另外,如果需要按热度或日期排序,此方法就没效果了,排序会引起mysql全表扫描。
如果你的更好的方案,或有什么问题,请留言! 
2017-06-10 09:30