View Javadoc
1   package examples.experimental.example3.classes;
2   
3   import java.io.IOException;
4   
5   import net.secodo.jcircuitbreaker.breaker.CircuitBreaker;
6   import net.secodo.jcircuitbreaker.breaker.impl.DefaultCircuitBreaker;
7   import net.secodo.jcircuitbreaker.breakhandler.BreakHandler;
8   import net.secodo.jcircuitbreaker.breakstrategy.BreakStrategy;
9   import net.secodo.jcircuitbreaker.exception.TaskExecutionException;
10  import net.secodo.jcircuitbreaker.task.Task;
11  import net.secodo.jcircuitbreaker.task.experimental.MethodInvokingTask;
12  
13  
14  public class MyCallerWithMethodInvokingTask {
15    private final PingService pingService;
16    private final CircuitBreaker<Void> circuitBreaker;
17    private final BreakHandler<Void> breakHandler;
18    private final BreakStrategy<Void> breakStrategy;
19  
20    public MyCallerWithMethodInvokingTask(BreakHandler<Void> breakHandler, BreakStrategy<Void> breakStrategy) {
21      this.pingService = new PingService();
22  
23      // prepare the circuit breaker
24      this.circuitBreaker = new DefaultCircuitBreaker<>();
25      this.breakStrategy = breakStrategy;
26      this.breakHandler = breakHandler;
27  
28    }
29  
30    public void ping(int pingId) throws IOException {
31      final Task<Void> task;
32      try {
33        task = new MethodInvokingTask(pingService, "sendPing", Void.class, pingId);
34      } catch (NoSuchMethodException e) {
35        throw new RuntimeException("Wrong method defintion passed to method invoking task", e);
36      }
37  
38      try {
39        circuitBreaker.execute(task, breakStrategy, breakHandler);
40      } catch (TaskExecutionException e) {
41        System.out.println("Calling ping resulted in exception: " + e.getTaskException());
42        throw new IOException(e.getTaskException().getMessage(), e.getTaskException());
43      }
44  
45    }
46  
47  }