当前位置:网站首页>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
- Sliding window based on count ( Default ,CircuitBreakerConfig It can be seen that )
- Time based sliding window
public enum SlidingWindowType {
TIME_BASED, COUNT_BASED
}
Four :CircuitBreakerConfig To configure
- 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;
- 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;
}
}
}
- 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);
}
- 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);
}
边栏推荐
- redis学习记录:字典(dict)源码分析
- Basic use of scratch
- 003:what does AWS think is a data lake?
- MYSQL的最左匹配原则的原理讲解
- Papaya Mobile: cross border marketing has entered the era of "information flow", allowing independent station sellers to share opportunities to go to sea
- Implementation of fruit mall wholesale platform based on SSM
- SAP HANA 错误消息 SYS_XSA authentication failed SQLSTATE - 28000
- Auto. JS learning note 4: after autojs is packaged, most Huawei and other big brand mobile phones cannot be installed? This problem can be solved by using the simulator to remotely sign and package in
- CentOS 7 installing MySQL 8
- markdown_ Picture side by side scheme
猜你喜欢

In 2026, the capacity of China's software defined storage market will be close to US $4.51 billion

C 语言仅凭自学能到什么高度?

Quickly build oncyber io

List of computer startup shortcut keys

7-13 underground maze exploration (adjacency table)

在线电路仿真以及开源电子硬件设计介绍

MySQL索引常见问题

Explanation of the principle of MySQL's leftmost matching principle

True north reading notes

UE4_ Explore the method of creating background scenes with ready-made resources
随机推荐
Periodic pains of cross-border e-commerce? Papaya mobile power as an independent station enabler
[cloud native | kubernetes] kubernetes networkpolicy
How high can C language reach by self-study alone?
Enumerate all USB device codes
FPGA基于DE2-115平台的VGA显示
1268_FreeRTOS任务上下文切换的实现
7-5 哲哲打游戏
MYSQL的最左匹配原则的原理讲解
PostgreSQL uses stored procedures to splice multiple tables and query data
C# break continue return 三者区别
Quickly build oncyber io
The white paper "protecting our digital heritage: DNA data storage" was released
postgresql 使用存储过程,拼接多张表,查询数据
Research progress of DNA digital information storage
[926. flip the string to monotonic increment]
Auto. JS learning note 9: basic methods such as using the script engine, starting the script file with the specified path, and closing
CEPH performance optimization and enhancement
C # getting started series (12) -- string
Web3.0与数字时尚,该如何落地?
Access and traversal of string class objects