SpringBoot+AOP+自定义注解实现接口耗时时间统计

SpringBoot+AOP+自定义注解实现接口耗时时间统计

1、导包


<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-aopartifactId>
dependency>

2、自定义注解

package com.base.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME)
@Target(METHOD)
public @interface CountTime {
}

3、定义切点和通知

package com.base.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 定义切点与通知
 */
@Aspect
@Component
@Slf4j
public class AopConfig {
    /**
     * 切点(表示只有加了@CountTime注解的方法,才会有统计接口耗时信息)
     */
    @Pointcut("@annotation(com.base.annotation.CountTime)")
    public void couTime() {

    }

    /**
     * 通知
     */
    @Around("couTime()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {//环绕通知
        long start = System.currentTimeMillis();
        Object res = proceedingJoinPoint.proceed();
        long result = System.currentTimeMillis()-start;
        log.info("方法{}耗时:{}毫秒",proceedingJoinPoint.getSignature().getName(),result);
        return res;
    }

}

4、Controller代码

package com.base.controller;

import com.base.annotation.CountTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class HelloController {

    @RequestMapping("/hello")
    @CountTime
    public String hello(){
        log.info("hello");
        return "hello";
    }

    @RequestMapping("/hello2")
    public String hello2(){
        log.info("hello2");
        return "hello2";
    }

    @RequestMapping("/hello3")
    public String hello3(){
        log.info("hello3");
        return "hello3";
    }
}

5、测试(只有hello接口加了注解@CountTime,所以只有hello接口能看到耗时日志信息)

浏览器依次访问:
http://localhost:8002/hello
http://localhost:8002/hello2
http://localhost:8002/hello3
在这里插入图片描述

你可能感兴趣的:(AOP,springboot,spring,boot,java)