AOP实现执行时间统计

本文介绍了如何使用Spring AOP在Com.wlb.file.service.impl包下的类方法执行前后添加日志记录,计算并输出接口耗时,帮助开发者理解代码性能。通过@Aspect、@Pointcut和@Around注解,实现了对特定方法的自动性能计时。
摘要由CSDN通过智能技术生成
package com.wlb.file.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author: zk
 * @create 2022-08-02 15:47
 */
@Aspect
@Slf4j
@Component
public class CostTimeAspect {

    private static final String AOP_POINTCUT = "execution (public * com.wlb.file.service.impl.*.*(..))";

    @Pointcut(value = AOP_POINTCUT)
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object costTimeAround(ProceedingJoinPoint joinPoint) {
        Object obj = null;
        try {
            long beginTime = System.currentTimeMillis();
            obj = joinPoint.proceed();
            //获取方法名称
            String method = joinPoint.getSignature().getName();
            //获取类名称
            String class1 = joinPoint.getSignature().getDeclaringTypeName();
            //计算耗时
            long cost = System.currentTimeMillis() - beginTime;
            log.info("类:[{}],方法:[{}] 接口耗时:[{}]", class1, method, cost + "毫秒");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }

}

项目结构:

 

实现效果:

022-08-03 10:30:27.847  INFO 11028 --- [nio-8080-exec-3] com.wlb.file.aspect.CostTimeAspect       : 类:[com.wlb.file.service.impl.UserServiceImpl],方法:[getAll] 接口耗时:[3毫秒]
2022-08-03 10:31:37.146  INFO 11028 --- [nio-8080-exec-1] com.wlb.file.aspect.CostTimeAspect       : 类:[com.wlb.file.service.impl.UserphoneServiceImpl],方法:[selectUAndP] 接口耗时:[3毫秒]
2022-08-03 10:41:41.509  INFO 11028 --- [nio-8080-exec-9] com.wlb.file.aspect.CostTimeAspect       : 类:[com.wlb.file.service.impl.UserServiceImpl],方法:[getAll] 接口耗时:[8毫秒]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值