当前位置:网站首页>Circuitbreaker fuse of resilience4j - circuitbreakerconfig configuration

Circuitbreaker fuse of resilience4j - circuitbreakerconfig configuration

2022-06-12 10:10:00 Wang Rushuang

One . Why circuit breakers

When A The service call B service , When problems occur due to network reasons or self reasons ,A Will wait B Corresponding to , When more servers request resources , There will be more requests A wait for B Response , So there's a chain effect ( Avalanche effect ), Because the service A Too many threads cause the service to A Thread exhaustion leads to A Can't accept the request. There is a problem , The circuit breaker is to solve this problem

Two . What is a circuit breaker

The circuit breaker has three normal states : Fully open OPEN, half HALF_OPEN, close CLOSED, There are also two forced states that can be set by : Force not available DISABLED, Force open FORCED_OPEN.

3、 ... and : Type of sliding window

  1. Sliding window based on count ( Default ,CircuitBreakerConfig It can be seen that )
  2. Time based sliding window
    public enum SlidingWindowType {
        TIME_BASED, COUNT_BASED
    }

Four :CircuitBreakerConfig To configure

  1. CircuitBreakerConfig Class defines the related configuration and properties , Mainly as follows :
    // Threshold for request call failure , percentage . The default is 50%, Namely service A Call the service B, here B A failed call counts as a failed call 
    public static final int DEFAULT_FAILURE_RATE_THRESHOLD = 50; // Percentage
    // Threshold for slow calls , percentage 
    public static final int DEFAULT_SLOW_CALL_RATE_THRESHOLD = 100; // Percentage
    //  The duration of the fuse in the open state . The default is 60 second 
    public static final int DEFAULT_WAIT_DURATION_IN_OPEN_STATE = 60; // Seconds
    //  When the fuse is half open ring buffer size . Default 10, No more than this value can be passed through the request 
    public static final int DEFAULT_PERMITTED_CALLS_IN_HALF_OPEN_STATE = 10;
    //  The minimum value of the failure rate can be calculated when the fuse is closed , Default 100
    public static final int DEFAULT_MINIMUM_NUMBER_OF_CALLS = 100;
    // Sliding window size , When the fuse is closed ring buffer size 
    public static final int DEFAULT_SLIDING_WINDOW_SIZE = 100;
    // Slow call time , That is, when the service A Call the service B when ,B The execution time of is longer than 60 Seconds is a slow call 
    public static final int DEFAULT_SLOW_CALL_DURATION_THRESHOLD = 60; // Seconds
    // Type of sliding window , The default is count based  COUNT_BASED
    public static final SlidingWindowType DEFAULT_SLIDING_WINDOW_TYPE = SlidingWindowType.COUNT_BASED;
    public static final boolean DEFAULT_WRITABLE_STACK_TRACE_ENABLED = true;
    //  Whether to record the assertion that the request call failed , By default, all exceptions are logged 
    private static final Predicate<Throwable> DEFAULT_RECORD_EXCEPTION_PREDICATE = throwable -> true;
    // Ignore exceptions 
    private static final Predicate<Throwable> DEFAULT_IGNORE_EXCEPTION_PREDICATE = throwable -> false;
    // The default exception predicate counts all exceptions as failures.
    private Predicate<Throwable> recordExceptionPredicate = DEFAULT_RECORD_EXCEPTION_PREDICATE;
    // The default exception predicate ignores no exceptions.
    private Predicate<Throwable> ignoreExceptionPredicate = DEFAULT_IGNORE_EXCEPTION_PREDICATE;

    //  The default is false, Whether to automatically switch from open to half open , When waitDurationInOpenState Time goes by , Automatically from OPEN Switch to HALF_OPEN
    // true:waitDurationInOpenState When it's due open Automatically change to half_open
    //false, The status will not change to... Until there is another request half_open, Otherwise, even if waitDurationInOpenState The expiration status is still open    
    private boolean automaticTransitionFromOpenToHalfOpenEnabled = false;

  1. CircuitBreakerConfig utilize Builder Pattern Created CircuitBreakerConfig example , It also provides a method for dynamically setting properties
/**
     *  The constructor pattern 
     */
 public static class Builder {

        @Nullable
        private Predicate<Throwable> recordExceptionPredicate;
        @Nullable
        private Predicate<Throwable> ignoreExceptionPredicate;

        //  Request call failed , A collection that stores exception records 
        @SuppressWarnings("unchecked")
        private Class<? extends Throwable>[] recordExceptions = new Class[0];
        //  Request call failed , Ignore the collection of exception records 
        @SuppressWarnings("unchecked")
        private Class<? extends Throwable>[] ignoreExceptions = new Class[0];
		...
		// Create an instance and set properties 
        public Builder(CircuitBreakerConfig baseConfig) {
            this.waitIntervalFunctionInOpenState = baseConfig.waitIntervalFunctionInOpenState;
            ...
            this.writableStackTraceEnabled = baseConfig.writableStackTraceEnabled;
        }

		// Dynamically set the call failure threshold 
        public Builder slidingWindow(int slidingWindowSize, int minimumNumberOfCalls,
            SlidingWindowType slidingWindowType) {
			.... 
            if (slidingWindowType == SlidingWindowType.COUNT_BASED) {
                // If it is a sliding window based on count ,minimumNumberOfCalls Take the minimum of both 
                this.minimumNumberOfCalls = Math.min(minimumNumberOfCalls, slidingWindowSize);
            } else {
               // Based on time 
                this.minimumNumberOfCalls = minimumNumberOfCalls;
            }
        }
}
  1. CircuitBreakerConfig There are two ways to get Builder Object method : Use default and custom configurations
    /**
     * Returns a builder to create a custom CircuitBreakerConfig.
     * 1. Use the default configuration to create Builder object , obtain builder Objects can be based on builder The method provided changes the configuration 
     * @return a {@link Builder}
     */
    public static Builder custom() {
        return new Builder();
    }

    /**
     * Returns a builder to create a custom CircuitBreakerConfig based on another
     * CircuitBreakerConfig.
     *  2. Use the incoming custom configuration baseConfig Of builder object , obtain builder Objects can be based on builder The method provided changes the configuration 
     * @return a {@link Builder}
     */
    public static Builder from(CircuitBreakerConfig baseConfig) {
        return new Builder(baseConfig);
    }
  1. CircuitBreakerConfig It also provides a method to get the configuration , For example, get the type of sliding window :
    public SlidingWindowType getSlidingWindowType() {
        return slidingWindowType;
    }

Sum up : This class is for creating CircuitBreakerConfig example , Set and get CircuitBreaker To configure

yml File configuration reference

resilience4j.circuitbreaker:
  configs:
    default: # @CircuitBreaker Of name
      registerHealthIndicator: true  # Health monitoring 
      ringBufferSizeInClosedState: 2 #  Buffer size when fuse is closed , It does not limit the concurrency of threads , Before the state transition of the fuse occurs, all requests will call the back-end service ( The failure rate is not calculated until the buffer is full )
      ringBufferSizeInHalfOpenState: 1 #  Buffer size when fuse is half open , Will limit the concurrency of threads ( Only ringBufferSizeInHalfOpenState concurrent ),
                                      #  For example, the buffer is 10 Only... Will be allowed at a time 10 A request calls the back-end service 
                                      #  The reason why concurrency can be limited ,CircuitBreakerStateMachine Used AtomicInteger:this.permittedNumberOfCalls = new AtomicInteger(permittedNumberOfCallsInHalfOpenState);

      waitDurationInOpenState: 10s #  Time required for fuse from open to half open 
      failureRateThreshold: 50 #  The failure threshold of fuse opening or the same failure rate threshold used in the half open state 
      slowCallDurationThreshold: 600s #  Slow call time , Company s
      slowCallRateThreshold: 100 #  Proportional threshold for slow calls 
      eventConsumerBufferSize: 7 #  Event buffer size ???
      minimumNumberOfCalls: 4  # Default 100
#      slideWindowType: COUNT_BASED #  Configure the type of sliding window , The default is count_based
#      automaticTransitionFromOpenToHalfOpenEnabled: false #  The default is false, Whether to automatically switch from open to half open , When waitDurationInOpenState Time goes by , Automatically from OPEN Switch to HALF_OPEN
#                                                      # true:waitDurationInOpenState When it's due open Automatically change to half_open,
#                                                      # If false, The status will not change to... Until there is another request half_open, Otherwise, even if waitDurationInOpenState The expiration status is still open
      recordExceptions: #  Recorded exceptions 
        - org.springframework.web.client.HttpServerErrorException
        - java.io.IOException
        - java.util.concurrent.TimeoutException
        - org.springframework.web.client.ResourceAccessException
        - org.springframework.web.client.HttpClientErrorException
      ignoreExceptions: #  Ignored exception 
      recordFailurePredicate:  # It is used to judge which abnormalities should be counted as failures and included in the circuit breaker statistics , The default is Throwable type 

5、 ... and :CircuitBreakerProperties Reading configuration

CircuitBreakerProperties As read yml or properties In file "resilience4j.circuitbreaker" Configuration at the beginning

@ConfigurationProperties(prefix = "resilience4j.circuitbreaker")
public class CircuitBreakerProperties extends CircuitBreakerConfigurationProperties {

}

Defined CircuitBreaker Cut in sequence

public class CircuitBreakerConfigurationProperties extends
    io.github.resilience4j.common.circuitbreaker.configuration.CircuitBreakerConfigurationProperties {

    //   Second to none 
    private int circuitBreakerAspectOrder = Ordered.LOWEST_PRECEDENCE - 2;
...

Put the read configuration information into Map in

public class CircuitBreakerConfigurationProperties extends CommonProperties {

    private Map<String, InstanceProperties> instances = new HashMap<>();
    private Map<String, InstanceProperties> configs = new HashMap<>();
  ...
 }

Provides 3 Created in CircuitBreakerConfig Methods

    public CircuitBreakerConfig createCircuitBreakerConfig(String backendName,
        InstanceProperties instanceProperties,
        CompositeCustomizer<CircuitBreakerConfigCustomizer> compositeCircuitBreakerCustomizer) {
        //  If there is... In the configuration item baseConfig, Just go to configs Find baseConfig
        if (StringUtils.isNotEmpty(instanceProperties.getBaseConfig())) {
            InstanceProperties baseProperties = configs.get(instanceProperties.getBaseConfig());
            if (baseProperties == null) {
                throw new ConfigurationNotFoundException(instanceProperties.getBaseConfig());
            }
            // call buildConfigFromBaseConfig Method creation CircuitBreakerConfig
            //  take baseProperties Properties are merged into  instanceProperties
            return buildConfigFromBaseConfig(instanceProperties, baseProperties,
                compositeCircuitBreakerCustomizer,
                backendName);
        }
        //  establish CircuitBreakerConfig
        return buildConfig(custom(), instanceProperties, compositeCircuitBreakerCustomizer,
            backendName);
    }
原网站

版权声明
本文为[Wang Rushuang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010528030801.html