1. 程式人生 > 其它 >SpringBoot下使用AOP做日誌

SpringBoot下使用AOP做日誌

AOP實現介面執行時間的計算:

  • SpringBoot專案匯入spring-boot-starter-aop依賴
  • 編寫切面類
    • 類上加@Aspect註解,表明這是一個切面類
    • 類上加@Component,把切面交給Spring管理(我們要切的Controller/Service都是Spring容器的,切面要對它們起作用,就必須同樣進入容器)
    • 類內部配置切點表示式,比如@Pointcut("execution(* com.bravo.demo.controller.*.*(..))") 表示對com.bravo.demo.controller包下所有方法進行增強
    • 類內部編寫增強邏輯,通常使用@Before、@Around宣告這是一個增強,不同的註解增強的方式不同,比如@Before前置增強、@Around環繞增強

1、匯入AOP整合SpringBoot依賴

 <!--SpringBoot整合Aop依賴-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-aop</artifactId>
 </dependency>

2、編寫切面類:com.zhixi.config.aop.ApiTimeLogAspect

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;

/**
 * @ClassName ApiTimeLogAspect
 * @Author zhangzhixi
 * @Description
 * @Date 2022-4-15 10:42
 * @Version 1.0
 */
@Slf4j
/*第一步:宣告這是一個切面類*/
@Aspect
@Component
public class ApiTimeLogAspect {

    /**
     * 第二步:定義切點表示式,明確要對那些方法起作用(比如,只對com.bravo.demo.controller包的方法計算介面耗時)
     */
    @Pointcut("execution(* com.zhixi.controller.*.*(..))")
    public void controllerPointcut() {
    }

    /**
     * 第三步:1.通過引用切點表示式,明確這個增強的應用規則。 2.編寫增強邏輯
     *
     * @param proceedingJoinPoint 執行目標方法的引數
     * @return 返回目標方法的執行結果
     * @throws Throwable proceedingJoinPoint.proceed()方法丟擲的異常
     */
    @Around(value = "controllerPointcut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 記錄介面執行前的時間戳
        long startTime = System.currentTimeMillis();
        // 實際執行目標方法,類似動態代理的invoke()執行目標方法
        Object result = proceedingJoinPoint.proceed();
        // 計算介面耗時
        log.info("------------ 耗時: {} ms ------------", System.currentTimeMillis() - startTime);
        // 只做增強不做改變,還是要把介面原本的結果返回
        return result;
    }
}

3、啟動專案訪問介面即可