Java 实现滑动时间窗口限流算法
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
| package com.yzw.test;
import java.time.LocalTime; import java.util.*; import java.util.concurrent.ConcurrentHashMap;
public class SlideWindow {
private volatile static Map<String, List<Long>> MAP = new ConcurrentHashMap<>(); private SlideWindow() { }
public static synchronized Boolean isGo(String listId, int count, Long timeWindows) { long now = System.currentTimeMillis(); List<Long> list = MAP.computeIfAbsent(listId, k -> new LinkedList<>()); if (list.size() < count) { list.add(0, now); return true; }
if (now - list.get(count - 1) <= timeWindows) { return false; } else {
list.remove(count - 1); list.add(0, now); return true; }
}
public static void main(String[] args) throws InterruptedException { while (true) { System.out.println(LocalTime.now().toString() + SlideWindow.isGo("ListId", 10, 2000L)); Thread.sleep(10); }
}
}
|
总结: 其本质思想是转换概念,将原本问题的确定时间大小,进行次数限制。转换成确定次数大小,进行时间限制。
参考: :https://www.cnblogs.com/dijia478/p/13807826.html