SpringBoot之統計接口執行耗時


實現功能:使用AOP統計方法執行耗時

 

Maven依賴:

        <!--引入AOP依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

 

自定義注解(加上該注解的方法系統自動統計耗時):

復制代碼
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 統計耗時
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TakeTime {

}
復制代碼

 

TakeTimeAspect(使用AOP技術統計方法執行前后消耗時間):

復制代碼
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 耗時統計
 */
@Aspect
@Component
public class TakeTimeAspect {

    private static final Logger logger = LoggerFactory.getLogger(TakeTimeAspect.class);


    //統計請求的處理時間
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 帶有@TakeTime注解的方法
     */
    @Pointcut("@annotation(com.emi2c.mybatis.config.annotation.TakeTime)")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        //接收到請求,記錄請求內容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //記錄請求的內容
        logger.info("請求URL:" + request.getRequestURL().toString());
        logger.info("請求METHOD:" + request.getMethod());
    }

    @AfterReturning(returning = "ret", pointcut = "log()")
    public void doAfterReturning(Object ret) {
        //處理完請求后,返回內容
        logger.info("方法返回值:" + JSON.toJSONString(ret));
        logger.info("方法執行時間:" + (System.currentTimeMillis() - startTime.get()));
    }


}
復制代碼

 

使用示例:

復制代碼
    @TakeTime
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public List<User> findAll() {
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setUsername("user" + i);
            user.setPassword("password" + i);
            userList.add(user);
        }
        return userList;
    }
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM