1 |
package dk.thoerup.circuitbreaker;
|
2 |
|
3 |
import java.util.concurrent.atomic.AtomicInteger;
|
4 |
import java.util.concurrent.atomic.AtomicLong;
|
5 |
|
6 |
public class AccountingCircuitBreaker extends CircuitBreaker {
|
7 |
|
8 |
private AtomicInteger tripCount = new AtomicInteger(0); // how many times ahs the CB tripped
|
9 |
private AtomicInteger blockCount = new AtomicInteger(0); //how many times has this CB blocked a call that would otherwise go to the backend
|
10 |
private AtomicInteger totalFailureCount = new AtomicInteger(0); //how many times has the backend thrown an exception
|
11 |
private AtomicInteger totalCallCount = new AtomicInteger(0);
|
12 |
private AtomicLong lastTrip = new AtomicLong(0);
|
13 |
private long lastResetCounters = 0;
|
14 |
|
15 |
public AccountingCircuitBreaker(String name, int threshold, long timeoutMS) {
|
16 |
super(name, threshold, timeoutMS);
|
17 |
|
18 |
resetCounters();
|
19 |
}
|
20 |
|
21 |
@Override
|
22 |
public Object invoke(CircuitInvocation invocation) throws Exception {
|
23 |
Object result;
|
24 |
try {
|
25 |
totalCallCount.incrementAndGet();
|
26 |
result = super.invoke(invocation);
|
27 |
} catch (Exception e) {
|
28 |
if (e instanceof CircuitBreakerException) {
|
29 |
blockCount.incrementAndGet();
|
30 |
} else {
|
31 |
totalFailureCount.incrementAndGet();
|
32 |
}
|
33 |
throw e;
|
34 |
}
|
35 |
|
36 |
return result;
|
37 |
}
|
38 |
|
39 |
@Override
|
40 |
public void tripBreaker() {
|
41 |
super.tripBreaker();
|
42 |
tripCount.incrementAndGet();
|
43 |
lastTrip.set( System.currentTimeMillis() );
|
44 |
}
|
45 |
|
46 |
public int getTripCount() {
|
47 |
return tripCount.get();
|
48 |
}
|
49 |
|
50 |
public int getBlockCount() {
|
51 |
return blockCount.get();
|
52 |
}
|
53 |
|
54 |
public int getTotalFailureCount() {
|
55 |
return totalFailureCount.get();
|
56 |
}
|
57 |
|
58 |
public long getLastResetCounters() {
|
59 |
return lastResetCounters;
|
60 |
}
|
61 |
|
62 |
public long getLastTrip() {
|
63 |
return lastTrip.get();
|
64 |
}
|
65 |
|
66 |
public int getTotalCallCount() {
|
67 |
return totalCallCount.get();
|
68 |
}
|
69 |
|
70 |
public void resetCounters() {
|
71 |
tripCount.set(0);
|
72 |
blockCount.set(0);
|
73 |
totalFailureCount.set(0);
|
74 |
totalCallCount.set(0);
|
75 |
lastTrip.set(0);
|
76 |
|
77 |
lastResetCounters = System.currentTimeMillis();
|
78 |
}
|
79 |
|
80 |
}
|