1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map;
@Aspect @Component public class TakeTimeAspect {
ThreadLocal<Long> startTime = new ThreadLocal<>(); ThreadLocal<Long> endTime = new ThreadLocal<>();
@Pointcut("@annotation(com.aimc.paperreduction.common.annotation.TakeTimeLog)") public void TakeTime() {}
@Before("TakeTime()") public void doBefore(JoinPoint joinPoint) throws Throwable { TakeTimeLog timeLog = getAnnotationLog(joinPoint); if (timeLog == null) { return; }
startTime.set(System.currentTimeMillis()); }
@AfterReturning(returning = "ret", pointcut = "TakeTime()") public void doAfterReturning(JoinPoint joinPoint, Object ret) { Map<String, Object> resultMap = new HashMap<>(); String[] names = ((CodeSignature) joinPoint.getSignature()).getParameterNames(); if (names.length > 0) { for (int i = 0; i < names.length; i++) { if (!(joinPoint.getArgs()[i] instanceof HttpServletRequest)) { resultMap.put(names[i], joinPoint.getArgs()[i]); } } } log.info("Return:" + JSON.toJSONString(ret)); endTime.set(System.currentTimeMillis()); log.info("Execution Time:" + (endTime.get() - startTime.get())); }
private TakeTimeLog getAnnotationLog(JoinPoint joinPoint) throws Exception { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod();
if (method != null) { return method.getAnnotation(TakeTimeLog.class); } return null; } }
|