-3

如果特定事件在给定的时间间隔内发生“X”次,我有一个用例来停止进程。

java spring 框架中是否有机制来处理这个问题?

4

2 回答 2

3

The question is quite general, so some general advice:

  1. Use a TreeSet<Long> of timestamps when the event happened;
  2. at each event occurence, add its timestamp to the set and remove all the expired entries (older than timeout);
  3. react when the set size grows above your threshold.

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 { }
于 2013-01-18T14:24:29.977 回答
0

由于您上面的示例显示了相当低的事件率(5 分钟内 10 个事件),我将创建一个 X 时间戳队列。到达的每条新消息:

  1. 如果队列已满,则退出队列
  2. 将当前时间戳推送到队列中
  3. 如果堆栈已满并且第 X 个时间戳和第一个时间戳之间的差异在给定的时间间隔内,则发出警报!
于 2013-01-18T14:35:40.953 回答