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
| @Aspect @Component public class RedisAccessAspect { private static final int WINDOW_SIZE_SECONDS = 60; private TimeWindowCounter counter = new TimeWindowCounter(WINDOW_SIZE_SECONDS); @Around("execution(* org.springframework.data.redis.core.RedisTemplate.*(..))") public Object around(ProceedingJoinPoint point) throws Throwable { String key = extractKey(point); counter.increment(key); return point.proceed(); } }
public class TimeWindowCounter { private Queue<Map<String, AtomicInteger>> windows = new LinkedList<>(); private final int windowSize; public void increment(String key) { getCurrentWindow().computeIfAbsent(key, k -> new AtomicInteger()).incrementAndGet(); } public Map<String, Integer> getTopKeys(int n) { return mergeWindows().entrySet().stream() .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue())) .limit(n) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new )); } }
|