想要一个能监控Spring项目内部方法的监控器,看看调用次数,最大最小时间,平均时间等一些数据,数据5分钟统计一次就可以。找了一圈没找到合适的,就自己撸了一个。
原理
- 使用者在外面用AOP拦截需要监控的方法。我是使用一个自定义的注解作为拦截条件。
- 使用Around方式声明AOP,并在拦截中调用Monitor的方法。
@Aspect
@Component
public class PerformanceAop {
@Autowired
Monitor monitor;
@Around("@annotation(MonitorMethod)")
public Object whenMethodCall(ProceedingJoinPoint joinPoint){
try {
return monitor.newInvoke(joinPoint);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
- 导入Bean
@ComponentScan(basePackages = {"io.github.bobdeng"})
- Maven引用
<dependency>
<groupId>io.github.bobdeng</groupId>
<artifactId>appmonitor</artifactId>
<version>0.3.4.SNAPSHOT</version>
</dependency>
- 然后访问http://yourip:yourport/monitor/list 得到Json的结果如下:
[
{
"className": "cn.v5.match.bean.impl.MatchServerImpl",
"methodName": "void cn.v5.match.bean.impl.MatchServerImpl.runLoop()",
"lastMonitorData": [
{
"max": 58,
"min": 0,
"times": 41,
"time": "2016-12-27 15:35",
"average": 2
}
]
}
]
- 可以专门用一个监控服务器从这个接口拉取数据,然后提供分析、告警、保存的功能。
- github https://github.com/bobdeng/appmonitor