自定义注解日志耗时统计

自定义注解日志耗时统计

自定义注解


@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ServiceMonitor {
}

自定义AOP

@Aspect
@Component
public class ServiceMonitorAspect {

/**
     * 切点
     *  @annotation(com.alibaba.cloud.retail.item.normal.openapi.common.monitor.ServiceMonitor):匹配所有的方法上拥有ServiceMonitor注解的方法外部调用
     * @within(com.alibaba.cloud.retail.item.normal.openapi.common.monitor.ServiceMonitor) : 匹配所有类上拥有ServiceMonitor注解的方法外部调用
     */
    @Pointcut("@annotation(com.zh.aop.ServiceMonitor)" + "|| @within(com.zh.aop.ServiceMonitor)")
    public void pointCut() {
    }


/**
* 环绕通知
*/
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            Object proceed = joinPoint.proceed();
            stopWatch.stop();
            String className = joinPoint.getTarget().getClass().getSimpleName();
            System.out.println("ServiceMonitorAspect_simpleName:{}"+className + "#"+joinPoint.getSignature().getName()+", timeMillis:{} ms"+stopWatch.getTotalTimeMillis());
            return  proceed;
        } catch (Throwable t) {
            System.out.println("ServiceMonitorAspect_error:"+ t);
            return ResultWrapper.fail("CATEGORY-F-001-00-99-001", "系统异常,请稍后重试");
        }
    }
}

使用


@ServiceMonitor
@Service
public class DemoServiceImpl implements DemoService {
    @Override
    public void hello() {
        System.out.println("DemoServiceImpl_hello");
        hello2();
    }

    public void hello2(){
        System.out.println("DemoServiceImpl_hello2");
    }
}

注意:@within 匹配所有类上拥有ServiceMonitor注解的方法外部调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值