user2585494
user2585494

Reputation: 611

Circuit breaker design pattern implementation

I have tried unsuccessfully to implement circuit breaker pattern, here, in Java using Spring framework.

How can you implement circuit breaker pattern by Java and Spring?

Upvotes: 20

Views: 34721

Answers (7)

Jonathan
Jonathan

Reputation: 5107

For a simple, straightforward circuit breaker implementation, check out Failsafe (which I authored). Ex:

CircuitBreaker breaker = new CircuitBreaker()
  .withFailureThreshold(5)
  .withSuccessThreshold(3)
  .withDelay(1, TimeUnit.MINUTES);

Failsafe.with(breaker).run(() -> connect());

Doesn't get much simpler.

Upvotes: 20

Roon
Roon

Reputation: 81

resilience4j is also a implementation of circuit breaker for java.

you can use 'circuit breaker', 'retry'.

guide: https://resilience4j.readme.io/docs/circuitbreaker

Upvotes: 0

svarog
svarog

Reputation: 9839

Apache commons has some implementations for several types of lightweight circuit breakers, here's a link to the docs

The project provides the EventCountCircuitBreaker and ThresholdCircuitBreaker classes, and an abstract AbstractCircuitBreaker so you could implement your own.

The code is open sources and is hosted at github, so anyone attempting to implement the pattern should at least take a peek.

Upvotes: 14

walkeros
walkeros

Reputation: 4942

You can have a look at JCircuitBreaker . The implementation there implements circuit breaker like approach.

Please note that this is not 1:1 implementation of the pattern because it does not define fixed states like "half-open". Instead it makes the decision (if the breaker should be open or closed) basing on current application state (using so called "break strategy"). Nevertheless it should be possible to define such a "break strategy" which evaluates failures thresholds - so it should be possible to also implement original pattern using JCircuitBreaker.

Upvotes: 2

Mark McLaren
Mark McLaren

Reputation: 11540

You don't actually need to be using Spring cloud or Spring boot to use Hystrix.
Using hystrix-javanica makes it easy to use Hystrix with plain old Spring too.

Here is an example of fallback methods (both methods, getMessageTimeout and getMessageException, fail by default):

@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class CircuitBreakingWithHystrix {

  @Bean
  public HystrixCommandAspect hystrixAspect() {
    return new HystrixCommandAspect();
  }

  public static void main(String[] args) throws Throwable {
    ApplicationContext ctx
      = new AnnotationConfigApplicationContext(CircuitBreakingWithHystrix.class);
    ExampleService ex = ctx.getBean(ExampleService.class);
    for (int i = 0; i < 1000; i++) {
      System.out.println(ex.getMessageException());
      System.out.println(ex.getMessageTimeout());
    }
  }

  @Service
  class ExampleService {

    /*
     * The default Hystrix timeout is 1 second. So the default 
     * version of this method will always fail.  
     * Adding the @HystrixProperty will cause 
     * the method to succeed.
     */
    @HystrixCommand(
      commandProperties = { 
      //@HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS,
      //                 value = "5000")
      },
      fallbackMethod = "messageFallback"
    )
    public String getMessageTimeout() {
      try {
        //Pause for 4 seconds
        Thread.sleep(4000);
      } catch (InterruptedException ex) {
        // Do something clever with this
      }
      return "result";
    }

    @HystrixCommand(
      fallbackMethod = "messageFallback")
    public String getMessageException() {
      throw new RuntimeException("Bad things happened");
    }

    private String messageFallback(Throwable hre) {
      return "fallback";
    }

  }

You can also examine the throwable sent to the fallback method to identify why the method call failed.

Upvotes: 2

Guillaume
Guillaume

Reputation: 18865

Spring cloud provides some interesting integration with Hystrix. You should probably have a look into it...

Upvotes: 5

Dawid Bugajewski
Dawid Bugajewski

Reputation: 375

Regarding the pattern itself

You can obtain a lot of useful information about this pattern at Martin Fowler's blog. It contains ruby implementation as well as references for implementation in other languages.

Regarding the java spring implementation

Please check the JRugged library. It contains the Circuit Breaker implementation in spring as well as other design patterns.

Upvotes: 4

Related Questions