1 |
package dk.thoerup.curcuitbreaker; |
2 |
|
3 |
import java.util.logging.Logger; |
4 |
|
5 |
/* Simple CircuitBreaker implementation - snipped from http://www.jroller.com/kenwdelong/entry/circuit_breaker_in_java |
6 |
* |
7 |
* example of how it can be used |
8 |
|
9 |
private CircuitBreaker cb = new CircuitBreaker("test", 5, 10000); |
10 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
11 |
class TestInvocation implements CircuitInvocation { |
12 |
String url; |
13 |
public TestInvocation(String url) { |
14 |
this.url = url; |
15 |
} |
16 |
public Object proceed() throws Exception{ |
17 |
|
18 |
URL u = new URL(url); |
19 |
URLConnection c = u.openConnection(); |
20 |
c.connect(); |
21 |
InputStream in = c.getInputStream(); |
22 |
in.close(); |
23 |
|
24 |
|
25 |
return "hello"; |
26 |
} |
27 |
|
28 |
} |
29 |
try { |
30 |
String s = (String) cb.invoke(new TestInvocation("http://rafiki/test")); |
31 |
response.getWriter().print(s); |
32 |
} catch (Throwable e) { |
33 |
logger.warning( e.getMessage() ); |
34 |
response.sendError(500); |
35 |
return; |
36 |
} |
37 |
|
38 |
} |
39 |
*/ |
40 |
|
41 |
|
42 |
public class CircuitBreaker{ |
43 |
Logger logger = Logger.getLogger(CircuitBreaker.class.getName()); |
44 |
|
45 |
|
46 |
private CircuitBreakerState currentState; |
47 |
|
48 |
private OpenState open = new OpenState(); |
49 |
private HalfOpenState halfOpen = new HalfOpenState(); |
50 |
private ClosedState closed = new ClosedState(); |
51 |
|
52 |
private String name; |
53 |
|
54 |
public CircuitBreaker(String name, int threshold, long timeoutMS) { |
55 |
closed.setThreshold(threshold); |
56 |
open.setTimeout(timeoutMS); |
57 |
|
58 |
this.name = name; |
59 |
|
60 |
reset(); |
61 |
} |
62 |
|
63 |
|
64 |
public Object invoke(CircuitInvocation invocation) throws Throwable |
65 |
{ |
66 |
Object result = null; |
67 |
try |
68 |
{ |
69 |
getState().preInvoke(this); |
70 |
result = invocation.proceed(); |
71 |
getState().postInvoke(this); |
72 |
} |
73 |
catch(Throwable t) |
74 |
{ |
75 |
getState().onError(this, t); |
76 |
throw t; |
77 |
} |
78 |
return result; |
79 |
} |
80 |
|
81 |
public void tripBreaker() { |
82 |
synchronized(this) { |
83 |
currentState = open; |
84 |
open.trip(); |
85 |
|
86 |
logger.warning("Circuitbreaker tripBreaker - " + name); |
87 |
} |
88 |
|
89 |
} |
90 |
|
91 |
public void attemptReset() { |
92 |
synchronized(this) { |
93 |
currentState = halfOpen; |
94 |
|
95 |
logger.warning("Circuitbreaker attemptReset - " + name); |
96 |
} |
97 |
} |
98 |
|
99 |
public void reset() { |
100 |
synchronized(this) { |
101 |
currentState = closed; |
102 |
|
103 |
logger.warning("Circuitbreaker reset - " + name); |
104 |
} |
105 |
} |
106 |
|
107 |
private CircuitBreakerState getState() { |
108 |
synchronized(this) { |
109 |
return currentState; |
110 |
} |
111 |
} |
112 |
} |