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