View Javadoc
1   package examples.example2.classes;
2   
3   import java.io.IOException;
4   import java.util.HashSet;
5   
6   import net.secodo.jcircuitbreaker.breaker.CircuitBreaker;
7   import net.secodo.jcircuitbreaker.breaker.impl.DefaultCircuitBreaker;
8   import net.secodo.jcircuitbreaker.breakhandler.BreakHandler;
9   import net.secodo.jcircuitbreaker.breakstrategy.BreakStrategy;
10  import net.secodo.jcircuitbreaker.breakstrategy.impl.LimitedCurrentAverageExecutionTimeStrategy;
11  import net.secodo.jcircuitbreaker.breakstrategy.impl.SingleExecutionAllowedStrategy;
12  import net.secodo.jcircuitbreaker.exception.TaskExecutionException;
13  import net.secodo.jcircuitbreaker.task.VoidTask;
14  
15  
16  public class MyCallerWithCircuitBreaker {
17    private final PingService pingService;
18    private final CircuitBreaker<Void> circuitBreaker;
19    private final BreakHandler<Void> breakHandler;
20    private final BreakStrategy<Void> breakStrategy;
21  
22    public MyCallerWithCircuitBreaker(final HashSet<Integer> failedPings) {
23      BreakHandler<Void> breakHandler = (circuitBreaker, task, breakStrategy, executionContext) -> {
24        failedPings.add(task.hashCode());
25        return null;
26      };
27  
28      BreakStrategy<Void> breakStrategy = new LimitedCurrentAverageExecutionTimeStrategy<Void>(700);
29      //BreakStrategy<Void> breakStrategy = new SingleExecutionAllowedStrategy<>();
30  
31      this.pingService = new PingService();
32  
33      // prepare the circuit breaker
34      this.circuitBreaker = new DefaultCircuitBreaker<>();
35      this.breakStrategy = breakStrategy;
36      this.breakHandler = breakHandler;
37    }
38  
39    public void ping(int pingId) throws IOException {
40      try {
41        circuitBreaker.execute((VoidTask) () -> pingService.sendPing(pingId), breakStrategy, breakHandler);
42      } catch (TaskExecutionException e) {
43        System.out.println("Calling ping resulted in exception: " + e.getTaskException());
44        throw new IOException(e.getTaskException().getMessage(), e.getTaskException());
45      }
46  
47    }
48  
49  }