断路器设计模式实现

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

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

对于简单,直接的断路器实现 ,请查看故障保险 。 例如:

CircuitBreaker breaker = new CircuitBreaker() .withFailureThreshold(5) .withSuccessThreshold(3) .withDelay(1, TimeUnit.MINUTES); Failsafe.with(breaker).run(() -> connect()); 

没有那么简单。

Apache commons有几种类型的轻量级断路器的实现,这里是文档的链接

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

代码是开源的,并在github上托管 ,因此任何试图实现该模式的人都应该至少看一眼。

Spring云提供了一些与Hystrix有趣的集成。 你可能应该看看它……

关于模式本身

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

关于java spring实现

请检查JRugged库 。 它包含Spring中的断路器实现以及其他设计模式。

您实际上不需要使用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,以确定方法调用失败的原因。

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

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