|
2 | 2 |
|
3 | 3 | import java.util.Date;
|
4 | 4 |
|
| 5 | +import com.google.common.collect.ConcurrentHashMultiset; |
| 6 | + |
5 | 7 | import lombok.AccessLevel;
|
6 | 8 | import lombok.Getter;
|
7 | 9 |
|
8 |
| -import com.google.common.collect.ConcurrentHashMultiset; |
| 10 | +public class LoggingRateLimiter<T> { |
9 | 11 |
|
| 12 | + @Getter(AccessLevel.PACKAGE) |
| 13 | + private volatile ConcurrentHashMultiset<T> frequency = ConcurrentHashMultiset.create(); |
| 14 | + private volatile Date lastCleared = new Date( |
| 15 | + 0); |
| 16 | + private final int limit; |
10 | 17 |
|
11 |
| -public class LoggingRateLimiter<T> { |
| 18 | + public LoggingRateLimiter(int limit) { |
| 19 | + this.limit = limit; |
| 20 | + } |
| 21 | + |
| 22 | + public LoggingRateLimiter() { |
| 23 | + this.limit = (60 * 1000 * 60); |
| 24 | + } |
| 25 | + |
| 26 | + public void addAndEnsureFrequency(T clazz) { |
| 27 | + resetAfterLimit(); |
| 28 | + frequency.add(clazz); |
| 29 | + } |
| 30 | + |
| 31 | + public void resetAfterLimit() { |
| 32 | + if (System.currentTimeMillis() - limit > lastCleared.getTime()) { |
| 33 | + frequency = ConcurrentHashMultiset.create(); |
| 34 | + lastCleared = new Date( |
| 35 | + System.currentTimeMillis()); |
| 36 | + } |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | + public void capacityAvailable(T t, long max, Runnable run) { |
| 41 | + if (frequency.count(t) < max) |
| 42 | + run.run(); |
12 | 43 |
|
13 |
| - @Getter(AccessLevel.PACKAGE) |
14 |
| - private volatile ConcurrentHashMultiset<T> frequency = ConcurrentHashMultiset.create(); |
15 |
| - private volatile Date lastCleared = new Date(0); |
16 |
| - private final int limit; |
17 |
| - |
18 |
| - public LoggingRateLimiter(int limit){ |
19 |
| - this.limit = limit; |
20 |
| - } |
21 |
| - |
22 |
| - public LoggingRateLimiter(){ |
23 |
| - this.limit=(60 *1000*60); |
24 |
| - } |
25 |
| - |
26 |
| - public void addAndEnsureFrequency(T clazz){ |
27 |
| - resetAfterLimit(); |
28 |
| - frequency.add(clazz); |
29 |
| - } |
30 |
| - public void resetAfterLimit(){ |
31 |
| - if (System.currentTimeMillis() - limit > lastCleared.getTime()){ |
32 |
| - frequency = ConcurrentHashMultiset.create(); |
33 |
| - lastCleared = new Date(System.currentTimeMillis()); |
34 |
| - } |
35 |
| - |
36 |
| - } |
37 |
| - |
38 |
| - public void capacityAvailable(T t, int max, Runnable run){ |
39 |
| - if(frequency.count(t) < max) |
40 |
| - run.run(); |
41 |
| - |
42 |
| - } |
| 44 | + } |
43 | 45 |
|
44 | 46 | }
|
0 commit comments