|
| 1 | +package com.tnt.common; |
| 2 | + |
| 3 | +import java.util.concurrent.ConcurrentHashMap; |
| 4 | + |
| 5 | +import org.aspectj.lang.ProceedingJoinPoint; |
| 6 | +import org.aspectj.lang.annotation.Around; |
| 7 | +import org.aspectj.lang.annotation.Aspect; |
| 8 | +import org.springframework.context.annotation.Profile; |
| 9 | +import org.springframework.stereotype.Component; |
| 10 | +import org.springframework.util.StopWatch; |
| 11 | + |
| 12 | +import lombok.extern.slf4j.Slf4j; |
| 13 | + |
| 14 | +@Aspect |
| 15 | +@Slf4j |
| 16 | +@Profile({"local", "dev"}) |
| 17 | +@Component |
| 18 | +public class ControllerExecutionTimeAspect { |
| 19 | + |
| 20 | + private final ConcurrentHashMap<String, MethodStats> methodStats = new ConcurrentHashMap<>(); |
| 21 | + |
| 22 | + @Around("@within(org.springframework.web.bind.annotation.RestController)") |
| 23 | + public Object aroundControllerExecutionTimeLogging(ProceedingJoinPoint joinPoint) throws Throwable { |
| 24 | + String className = joinPoint.getSignature().getDeclaringTypeName(); |
| 25 | + String methodName = joinPoint.getSignature().getName(); |
| 26 | + String fullMethodName = className + "." + methodName; |
| 27 | + |
| 28 | + StopWatch sw = new StopWatch(); |
| 29 | + |
| 30 | + sw.start(); |
| 31 | + Object result = joinPoint.proceed(); |
| 32 | + sw.stop(); |
| 33 | + |
| 34 | + methodStats.computeIfAbsent(fullMethodName, k -> new MethodStats()) |
| 35 | + .recordExecutionTime(sw.getTotalTimeMillis()); |
| 36 | + |
| 37 | + MethodStats stats = methodStats.get(fullMethodName); |
| 38 | + |
| 39 | + log.info("Execution time of {} is {} ms", fullMethodName, sw.getTotalTimeMillis()); |
| 40 | + log.info("{} stats: {}", fullMethodName, stats); |
| 41 | + |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + private static class MethodStats { |
| 46 | + |
| 47 | + private long count; |
| 48 | + private long totalTime; |
| 49 | + private long minTime = Long.MAX_VALUE; |
| 50 | + private long maxTime; |
| 51 | + |
| 52 | + public synchronized void recordExecutionTime(long time) { |
| 53 | + count++; |
| 54 | + totalTime += time; |
| 55 | + minTime = Math.min(minTime, time); |
| 56 | + maxTime = Math.max(maxTime, time); |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public String toString() { |
| 61 | + return String.format("count: %d, average: %dms, min: %dms, max: %dms", count, totalTime, minTime, maxTime); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments