bitscn.com下面是mysql占用cpu高处理的一个例子,希望对遇到类似问题的朋友们有点启发。一般来说myql占用cpu高,多半是数据库查询代码问题,查询数据库过多。所以一方面要精简代码,另一方面最好对频繁使用的代码设置索引。
今天早上起来 机器报警 一查负载一直都在4以上
top了一下 发现 mysql 稳居 第一 而且相当稳定 我擦 
重启一下mysql不行 
mysql> show processlist;一下 
发现xxx网站有两条 查询语句 一直 在列,我擦 该站 也就30多万条记录 量也不大 不可能是机器性能问题
忽然 记得以前在网上看过说是 tmp_table_size值太小会造成这种情况; 
于是mysql -pxxx -e show variables; >tmp 
一看是默认的32m(显示出来的是字节数) 
于是翁就开心的改了起来 增加到256 重启 mysql 。。结果很失望
不行啊 还得再来 
select 一下该表 发现 里面 都是论坛留言的东西 量还挺大 
于是: 
mysql> show columns from bbs_message; 
+-----------+--------------+------+-----+---------+----------------+ 
| field | type | null | key | default | extra | 
+-----------+--------------+------+-----+---------+----------------+ 
| msg_id | int(11) | no | pri | null | auto_increment | 
| board_id | int(11) | no | mul | 0 | | 
| parent_id | int(11) | no | mul | 0 | | 
| root_id | int(11) | no | mul | 0 | |
一直在show processlist 里面出现的 就是 select * from bbs_message where board_id=xxx and parent_id=xxx 
和 select * from bbs_message where parent_id=xxx 
只要这两条一出现 cpu就上去了 
于是 从索引入手: 
增加两条索引 
mysql> alter table bbs_message add index parentid(parent_id); 
alter table bbs_message add index chaxunid(board_id,parent_id); 
最后查看一下索引结果: 
mysql> show index from bbs_message; 
+-------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 
| table | non_unique | key_name | seq_in_index | column_name | collation | cardinality | sub_part | packed | null | index_type | comment | 
+-------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 
| bbs_message | 0 | primary | 1 | msg_id | a | 2037 | null | null | | btree | | 
| bbs_message | 1 | rootid | 1 | root_id | a | 49 | null | null | | btree | | 
| bbs_message | 1 | chaxunid | 1 | board_id | a | 3 | null | null | | btree | | 
| bbs_message | 1 | chaxunid | 2 | parent_id | a | 135 | null | null | | btree | | 
| bbs_message | 1 | parentid | 1 | parent_id | a | 127 | null | null | | btree | | 
+-------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 
5 rows in set (0.00 sec) 
退出 在 top 一下 负载一直在0.x 很稳定bitscn.com
   
 
   