spring boot aop 记录方法执行时间代码示例
本文研究的主要是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
@Aspect
public 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 记录方法执行时间代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
您可能感兴趣的文章:
- 详解使用Spring Boot的AOP处理自定义注解
- Springboot 使用 JSR 303 对 Controller 控制层校验及 Service 服务层 AOP 校验 使用消息资源文件对消息国际化
- 浅谈SpringBoot集成Redis实现缓存处理(Spring AOP实现)
- Spring Boot学习入门之AOP处理请求详解
- 详解SpringBoot之集成Spring AOP
- 详解Spring Boot中使用AOP统一处理Web请求日志
- 详解SpringBoot AOP 拦截器(Aspect注解方式)
- spring boot如何使用spring AOP实现拦截器
赞 (0)
