CircuitBreaker



  • 重複コール障害の発生を防止するサービス

  • 一部のサービスが正常でない場合は、他の機能の代替を使用します->障害の回避



  • Hystrix->Resilience 4 jで置き換える
  • Resilience4j

  • resilience4j-circuitbreaker: Circuit breaking
  • resilience4j-ratelimiter: Rate limiting
  • resilience4j-bulkhead: Bulkheading
  • resilience4j-retry: Automatic retrying (sync and async)
  • resilience4j-timelimiter: Timeout handling
  • resilience4j-cache: Result caching
  • 使いやすい

  • pom.xml
  •         <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
            </dependency>
  • ユーザ-サービスgetUserByUserId()関数order-サービスを呼び出す部分
  • 
      private final CircuitBreakerFactory circuitBreakerFactory;
      
      ...
    public UserDto getUserByUserId() {
      ...
      
    // 주석
    //  List<ResponseOrder> orderList = orderServiceClient.getOrders(userId); 
    
      CircuitBreaker circuitBreaker = circuitBreakerFactory.create("circuitbreaker");
      List<ResponseOrder> orderList = circuitBreaker.run(() -> orderServiceClient.getOrders(userId),
                throwable -> new ArrayList<>());
    
    ...
    }
    

    カスタム

    package com.example.userservice.config;
    
    import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
    import io.github.resilience4j.timelimiter.TimeLimiterConfig;
    import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
    import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
    import org.springframework.cloud.client.circuitbreaker.Customizer;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.time.Duration;
    
    @Configuration
    public class Resilience4jConfig {
      @Bean
      public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration() {
        CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
          .failureRateThreshold(4)
          .waitDurationInOpenState(Duration.ofMillis(1000))
          .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
          .slidingWindowSize(2)
          .build();
    
        TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
          .timeoutDuration(Duration.ofSeconds(4))
          .build();
    
        return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
          .timeLimiterConfig(timeLimiterConfig)
          .circuitBreakerConfig(circuitBreakerConfig)
          .build()
        );
      }
    }