Spring中使用Annotation来记录方法的运行时间

在Spring的Java程序中,每个方法写一句log来记录这个方法执行多久是一件很恶心的事情。记录下使用annotation来解决。

1. 定义一个annotation

@Target({java.lang.annotation.ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogExecuteTime {

}

2. 然后写一个Aspect:

@Aspect
@Component
public class LogTimeInterceptor {
	
	private static Logger logger = LoggerFactory.getLogger(LogTimeInterceptor.class);
	
	@Pointcut("@annotation(com.xxx.quartz.cluster.annotation.LogExecuteTime)")
	public void logTimeMethodPointcut() {
		
	}
	
	@Around("logTimeMethodPointcut()")
	public Object interceptor(ProceedingJoinPoint pjp) {
		long startTime = System.currentTimeMillis();
		
		Object result = null;
		try {
			result = pjp.proceed();
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
		
		logger.info(pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName() + " spend " + (System.currentTimeMillis() - startTime) + "ms");
		
		return result;
	}

}

3. 在需要记录执行时间的方法上加上这个annotation:

	@LogExecuteTime
	public long myMethod(List<Integer> keys) {
		return xxx;
	}

运行以后我们就能在log中看到了这个类的这个方法执行了多久。。如果还需要加其它参数,请修改上面的interceptor方法。

Spring Boot ,可以通过 AOP(面向切面编程)来记录程序运行时间。具体实现步骤如下: 1. 创建一个切面类,使用 @Aspect 注解标识该类为切面类。 2. 定义一个方法使用 @Around 注解标识该方法为环绕通知,即在目标方法执行前后都会执行该方法。 3. 在环绕通知方法使用 System.currentTimeMillis() 记录当前时间,执行目标方法,再次使用 System.currentTimeMillis() 记录当前时间,计算出程序运行时间。 4. 将程序运行时间记录到日志,可以使用 log4j2、slf4j 或者 Spring Boot 自带的日志框架。 下面是一个示例代码: ```java @Aspect @Component public class TimeAspect { private static final Logger logger = LoggerFactory.getLogger(TimeAspect.class); @Around("@annotation(com.example.demo.annotation.LogTime)") public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); Object result = joinPoint.proceed(); long end = System.currentTimeMillis(); logger.info("{} 方法执行时间为 {} ms", joinPoint.getSignature().getName(), end - start); return result; } } ``` 在上面的代码,我们使用了 @LogTime 注解来标识需要记录程序运行时间方法。在环绕通知方法使用了 ProceedingJoinPoint 类来执行目标方法,最后将程序运行时间记录到日志。 需要注意的是,为了使切面生效,需要在 Spring Boot 的配置类添加 @EnableAspectJAutoProxy 注解。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值