断路器设计模式实现

时间:2015-05-17 09:59:54

标签: java spring design-patterns

我尝试使用Spring框架在Java中实现断路器模式here失败。

如何通过Java和Spring实现断路器模式?

6 个答案:

答案 0 :(得分:10)

对于简单明了的circuit breaker implementation,请查看Failsafe。例如:

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

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

没有那么简单。

答案 1 :(得分:5)

http://example.net/user/123/values有几种轻量级断路器的实现,这里是Apache commons

该项目提供了ThresholdCircuitBreakerAbstractCircuitBreaker类,以及一个抽象的ICollection,因此您可以实现自己的类。

代码是开放源代码并且是a link to the docs,因此任何试图实现该模式的人都应该至少看一眼。

答案 2 :(得分:3)

Spring cloud提供了与Hystrix的有趣集成。你可能应该看看它......

答案 3 :(得分:1)

关于模式本身

您可以在Martin Fowler's blog获取有关此模式的大量有用信息。它包含ruby实现以及其他语言实现的参考。

关于java spring实现

请检查JRugged library。 它包含Spring中的Circuit Breaker实现以及其他设计模式。

答案 4 :(得分:1)

您实际上不需要使用Spring云或Spring启动来使用Hystrix 使用hystrix-javanica可以很容易地使用Hystrix和普通的Spring。

以下是回退方法的示例(默认情况下,这两个方法,getMessageTimeout和getMessageException都失败):

@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";
    }

  }

您还可以检查发送到回退方法的throwable,以确定方法调用失败的原因。

答案 5 :(得分:0)

您可以查看JCircuitBreaker。那里的实现实现了类似断路器的方法。

请注意,这不是模式的1:1实现,因为它没有定义像“半开”这样的固定状态。相反,它根据当前的应用状态(使用所谓的“中断策略”)做出决定(如果断路器应该打开或关闭)。尽管如此,应该可以定义一个评估故障阈值的“中断策略” - 因此应该可以使用JCircuitBreaker实现原始模式。

相关问题