首页 > 编程 > Java > 正文

spring boot aop 记录方法执行时间代码示例

2019-11-26 10:20:33
字体:
来源:转载
供稿:网友

本文研究的主要是spring boot aop 记录方法执行时间的实现代码,具体如下。

为了性能调优,需要先统计出来每个方法的执行时间,直接在方法前后log输出太麻烦,可以用AOP来加入时间统计

添加依赖

<dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-aop</artifactId></dependency>

在application.properties中加入配置

spring.aop.auto=true

spring.aop.auto属性默认是开启的,也就是说只要引入了AOP依赖后,默认已经增加了@EnableAspectJAutoProxy。 切记千万不要加入多余的信息,如@EnableAspectJAutoProxy!

实现具体代码

@Component@Aspectpublic class LogAspect {	private static final Log LOG = LogFactory.getLog(LogAspect.class);	/**   * 定义一个切入点.   * 解释下:   *   * ~ 第一个 * 代表任意修饰符及任意返回值.   * ~ 第二个 * 定义在web包或者子包   * ~ 第三个 * 任意方法   * ~ .. 匹配任意数量的参数.   */	@Pointcut("execution(* com.wedo.stream.service..*.*(..))")	   public void logPointcut(){	}	@org.aspectj.lang.annotation.Around("logPointcut()")	   public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{		//  	 LOG.debug("logPointcut " + joinPoint + "/t");		long start = System.currentTimeMillis();		try {			Object result = joinPoint.proceed();			long end = System.currentTimeMillis();			LOG.error("+++++around " + joinPoint + "/tUse time : " + (end - start) + " ms!");			return result;		}		catch (Throwable e) {			long end = System.currentTimeMillis();			LOG.error("+++++around " + joinPoint + "/tUse time : " + (end - start) + " ms with exception : " + e.getMessage());			throw e;		}	}}

注意问题

aop后方法不能正确返回值

这个代理方法一定要返回值,否则,在代码中就没有返回值了。

//这样是不对的 public void doAround(ProceedingJoinPoint joinPoint){}

Spring的文档中这么写的:Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理。所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理。

默认是JDK动态代理,更改为cglib

总结

以上就是本文关于spring boot aop 记录方法执行时间代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表