如果特定事件在给定的时间间隔内发生“X”次,我有一个用例来停止进程。
java spring 框架中是否有机制来处理这个问题?
The question is quite general, so some general advice:
TreeSet<Long>
of timestamps when the event happened; For 2. use the tailSet
method to quickly eliminate the expired timestamps.
This is a short example of the approach:
public class OverloadGuard {
private SortedSet<Long> timestamps = new TreeSet<>();
private final long timeout = TimeUnit.MINUTES.toMillis(5);
private final int threshold = 10;
public synchronized void event() {
final long now = System.currentTimeMillis();
timestamps = timestamps.tailSet(now - timeout);
timestamps.add(now);
if (timestamps.size() > threshold) throw new OverloadException();
}
}
class OverloadException extends RuntimeException { }
由于您上面的示例显示了相当低的事件率(5 分钟内 10 个事件),我将创建一个 X 时间戳队列。到达的每条新消息: