直接上代码 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455package demo;import java.time.LocalDateTime;import java.util.LinkedList;import java.util.Random;/** * @author weylan */public class SlideWindow { static LinkedList<long> timeWindow = new LinkedList<>(); /** * 滑动时间窗口限流算法 * 在指定时间窗口,指定限制次数内,是否允许通过 * * @param windowSize 时间窗口大小,单位 秒 * @param count 允许通过的次数 * @return 是否允许通过 */ public static boolean process(long windowSize, int count) { long nowTime = System.currentTimeMillis(); // 未达到限制次数,则允许通过,并添加当前时间戳到队列开始位置 if (timeWindow.size() < count) { timeWindow.addFirst(nowTime); return Boolean.TRUE; } // 队列已满(达到限制次数),则获取队列中最早(队尾)添加的时间戳 Long farTime = timeWindow.getLast(); // 用当前时间戳 减去 最早添加的时间戳 if (nowTime - farTime <= windowSize) { // 若结果小于等于windowSize,则说明在windowSize内,通过的次数大于count return false; } // 若结果大于windowSize,则说明在windowSize内,通过的次数小于等于count // 允许通过,并删除最早添加的时间戳,将当前时间添加到队首 timeWindow.removeLast(); timeWindow.addFirst(nowTime); return Boolean.TRUE; } public static void main(String[] args) throws InterruptedException { Random random = new Random(); while (true) { // 10秒只允许2次通过 System.out.println(LocalDateTime.now() + " : " + process(10000, 2)); // 睡眠 0~10秒 Thread.sleep(1000L * random.nextInt(10)); } }} 123456789101112131415161718192021222324252627282930313233343536373839402021-10-19T16:30:56.654 : true2021-10-19T16:30:56.655 : true2021-10-19T16:31:03.659 : false2021-10-19T16:31:09.663 : true2021-10-19T16:31:12.663 : true2021-10-19T16:31:20.667 : true2021-10-19T16:31:21.671 : false2021-10-19T16:31:21.671 : false2021-10-19T16:31:26.675 : true2021-10-19T16:31:27.679 : false2021-10-19T16:31:29.680 : false2021-10-19T16:31:38.682 : true2021-10-19T16:31:47.686 : true2021-10-19T16:31:56.690 : true2021-10-19T16:31:58.695 : true2021-10-19T16:32:04.696 : false2021-10-19T16:32:11.698 : true2021-10-19T16:32:11.698 : true2021-10-19T16:32:11.698 : false2021-10-19T16:32:15.702 : false2021-10-19T16:32:21.705 : true2021-10-19T16:32:23.709 : true2021-10-19T16:32:32.708 : true2021-10-19T16:32:40.711 : true2021-10-19T16:32:45.715 : true2021-10-19T16:32:50.719 : true2021-10-19T16:32:57.720 : true2021-10-19T16:32:59.722 : false2021-10-19T16:33:03.723 : true2021-10-19T16:33:11.727 : true2021-10-19T16:33:11.727 : false2021-10-19T16:33:16.731 : true2021-10-19T16:33:16.732 : false2021-10-19T16:33:17.735 : false2021-10-19T16:33:22.738 : true2021-10-19T16:33:28.741 : true2021-10-19T16:33:29.741 : false2021-10-19T16:33:30.744 : false