简体   繁体   English

断路器设计模式实现

[英]Circuit breaker design pattern implementation

I have tried unsuccessfully to implement circuit breaker pattern, here , in Java using Spring framework.我尝试在此处使用 Spring 框架在 Java 中实现断路器模式,但未成功。

How can you implement circuit breaker pattern by Java and Spring? Java和Spring如何实现断路器模式?

For a simple, straightforward circuit breaker implementation , check out Failsafe . 有关简单,直接的断路器实现 ,请查看故障保险 Ex: 例如:

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

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

Doesn't get much simpler. 没有那么简单。

Apache commons has some implementations for several types of lightweight circuit breakers, here's a link to the docs Apache commons有几种类型的轻量级断路器的实现,这里是文档的链接

The project provides the EventCountCircuitBreaker and ThresholdCircuitBreaker classes, and an abstract AbstractCircuitBreaker so you could implement your own. 该项目提供了EventCountCircuitBreakerThresholdCircuitBreaker类,以及一个抽象的AbstractCircuitBreaker因此您可以实现自己的类。

The code is open sources and is hosted at github , so anyone attempting to implement the pattern should at least take a peek. 代码是开源的,并在github托管 ,因此任何试图实现该模式的人都应该至少看一眼。

Spring cloud provides some interesting integration with Hystrix . Spring云提供了一些与Hystrix有趣的集成。 You should probably have a look into it... 你可能应该看看它......

Regarding the pattern itself 关于模式本身

You can obtain a lot of useful information about this pattern at Martin Fowler's blog . 您可以在Martin Fowler的博客上获得有关此模式的大量有用信息。 It contains ruby implementation as well as references for implementation in other languages. 它包含ruby实现以及其他语言的实现参考。

Regarding the java spring implementation 关于java spring实现

Please check the JRugged library . 请检查JRugged库 It contains the Circuit Breaker implementation in spring as well as other design patterns. 它包含Spring中的断路器实现以及其他设计模式。

You don't actually need to be using Spring cloud or Spring boot to use Hystrix. 您实际上不需要使用Spring云或Spring启动来使用Hystrix。
Using hystrix-javanica makes it easy to use Hystrix with plain old Spring too. 使用hystrix-javanica可以很容易地使用Hystrix和普通的Spring。

Here is an example of fallback methods (both methods, getMessageTimeout and getMessageException, fail by default): 以下是回退方法的示例(默认情况下,这两个方法,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";
    }

  }

You can also examine the throwable sent to the fallback method to identify why the method call failed. 您还可以检查发送到回退方法的throwable,以确定方法调用失败的原因。

You can have a look at JCircuitBreaker . 你可以看看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". 请注意,这不是模式的1:1实现,因为它没有定义像“半开”这样的固定状态。 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. 尽管如此,应该可以定义一个评估故障阈值的“中断策略” - 因此应该可以使用JCircuitBreaker实现原始模式。

resilience4j is also a implementation of circuit breaker for java. resilience4j 也是 java 断路器的实现。

you can use 'circuit breaker', 'retry'.您可以使用“断路器”、“重试”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM