首頁/ 汽車/ 正文

aop統計介面耗時

一、匯入相關依賴

org。springframework。boot spring-boot-starter-aop

aop統計介面耗時

二、建立自定義註解

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

aop統計介面耗時

三、建立切面

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@Componentpublic class TakeTimeAspect { private static final Logger logger = LoggerFactory。getLogger(TakeTimeAspect。class); //統計請求的處理時間 ThreadLocal startTime = new ThreadLocal<>(); /*** 帶有@TakeTime註解的方法*/ @Pointcut(“@annotation(xxx。xxx。xxx。config。annotation。TakeTime)”) public void log() { } @Before(“log()”) public void doBefore() throws Throwable { startTime。set(System。currentTimeMillis()); //接收到請求,記錄請求內容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder。getRequestAttributes(); HttpServletRequest request = attributes。getRequest(); //記錄請求的內容 logger。info(“請求URL:” + request。getRequestURL()。toString()); } @AfterReturning(returning = “ret”, pointcut = “log()”) public void doAfterReturning(Object ret) { //處理完請求後,返回內容 //logger。info(“方法返回值:” + JSON。toJSONString(ret)); logger。info(“方法執行時間:” + (System。currentTimeMillis() - startTime。get())); } }

aop統計介面耗時

三、在需要統計介面耗時的地方添加註解

@TakeTime

相關文章

頂部