本节概览:通过AOP切面,用户可以通过使用一个注解实现监控打点。
1 Spring配置文件
1 2 3 4 5 6 |
<!-- 指定切面类所在包 --> <context:component-scan base-package="monitorclient.aop" /> <mvc:annotation-driven/> <!-- 使用@Aspect定义切面 --> <aop:aspectj-autoproxy/> |
2 代码
2.1 注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Monitor { /** * 监控key * * @return */ String key(); /** * 失败信息,用于记录error log * * @return */ String errMessage() default ""; } |
2.2 定义切面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
@Aspect @Component public class MonitorAspect { private static final Logger LOGGER = LoggerFactory.getLogger(MonitorAspect.class); @Around("@annotation(monitor)") public Object execute(ProceedingJoinPoint proceedingJoinPoint, Monitor monitor) throws Throwable { Long startTime = System.currentTimeMillis(); try { Object result = proceedingJoinPoint.proceed(); LMonitor.recordOne(monitor.key(), System.currentTimeMillis() - startTime); LOGGER.info("monitor执行成功"); return result; } catch (Exception e) { LOGGER.error("执行失败", e); LMonitor.recordFail(monitor.key()); return "error"; } } } |
3 使用切面
在一个请求函数上面添加注解@Monitor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Controller public class HelloController { @Monitor(key = "testMonitor") @RequestMapping(value = "/testMonitor") public String testVelocityWithMonitor() { try { Thread.sleep(200); } catch (Exception e) { } return "helloJsp"; } } |
(全文完)