Circuit breaker design pattern implementation

后端 未结 6 1772
不思量自难忘°
不思量自难忘° 2020-12-24 08:37

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 Sp

6条回答
  •  一整个雨季
    2020-12-24 09:04

    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.

提交回复
热议问题