记一次CPU过高排查过程

2,275 阅读2分钟

存在的问题

上周突然在部署一点很简单的新业务之后,上线没多久突然OOM,大部分接口访问超时,甚至有的直接失败,刚开始以为是查询了什么了大数据导致的,结果看了下CPU,300%。

排查思路

最开始我先看了下日志,如下:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
### The error may exist in file [/Users/bingfeng/Documents/mochuCode/service-ecook/target/classes/mybatis/mapper/CollectionSortMapper.xml]
### The error may involve cn.ecook.core.mapper.CollectionSortMapper.selectTopSortCollectionWithDays
### The error occurred while handling results
### SQL: select sortid as id ,count(*) as `number` from `collection_sort_collection`          WHERE  createtime between concat(?, ' 00:00:00') and concat(?, ' 23:59:59')          group by sortid         order by `number` DESC LIMIT ?
### Cause: java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
	at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:92)
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:440)
	at com.sun.proxy.$Proxy97.selectList(Unknown Source)
	at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:223)
	at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:147)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:80)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:93)
	at com.sun.proxy.$Proxy166.selectTopSortCollectionWithDays(Unknown Source)

日志当时只有这种报错,最开始我以为这就是简单的索引越界异常,没在意,把这块问题过掉了。

分析CPU高的进程

到这里我们就需要通过堆栈信息去进行分析,看到底是哪里的出现了问题,下面是具体的步骤:

  • 根据进程号查询查看进程中各个线程的资源使用率
top -Hp 2159

这里的CPU是恢复后的,当时的结果CPU前三个都是99%。

  • 将线程id转换为16进制
printf "%x\n" 2205

  • 打印堆栈信息
jstack 2159 | grep -10 89d

通过下面的状态,可以发现,出现接口访问慢的原因是因为所有的线程阻塞导致的,再往下可以发现导致这些问题的原因是查询SQL导致的。那么我们就把最新提交的代码看看,哪里进行了SQL查询。

问题定位

通过排查发现,有这么一段代码,这是SQL查询结果的实体,就是因为使用了@Builder注解,没有显式的提供构造,才导致CPU一直飙升。

再使用Builder之后,一定要显式的声明构造方法

反思

出现这种问题我觉得就两个原因:

  • 1、自测不到位;
  • 2、规范不够(要是规范到位,实体类不可能出现没有构造的情况);