Introduction to fuse mode
The core idea of fuse mode isMonitoring service callsstatus. When the failure rate exceeds the threshold, the fuse will enter the "Open" state, and subsequent calls will directly return the preset downgrade result to avoid resource exhaustion. After a period of time, the fuse will try to enter a "half-open" state, allowing some requests to pass to detect whether the downstream service is restored.
Spring Cloud CircuitBreaker
Spring Cloud providesspring-cloud-starter-circuitbreaker
Abstract layer, supports multiple implementations (such as Resilience4j, Sentinel). The following isResilience4jAs an example.
Step 1: Add dependencies
existIntroduce dependencies:
<!-- Spring Cloud Circuit Breaker Starter --> <dependency> <groupId></groupId> <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId> </dependency> <!-- Actuator(Optional,For monitoring) --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
Step 2: Configure the fuse parameters
existConfigure Resilience4j:
resilience4j: circuitbreaker: configs: default: failureRateThreshold: 50 # The failure rate threshold for triggering the circuit breaker (%) minimumNumberOfCalls: 5 # Minimum number of calls to calculate the failure rate slidingWindowType: COUNT_BASED # Sliding window type (based on the number of calls) slidingWindowSize: 10 # Sliding window size waitDurationInOpenState: 5s # Waiting time after the fuse is turned on permittedNumberOfCallsInHalfOpenState: 3 # The number of calls allowed in the half-open state automaticTransitionFromOpenToHalfOpenEnabled: true # Automatically switch to half-open state
Step 3: Annotation with @CircuitBreaker
Add annotations on the method that needs to be fuse and specify a downgrade method:
import ; @Service public class UserService { @Autowired private CircuitBreakerFactory circuitBreakerFactory; public String getUserInfo(String userId) { return ("userServiceCircuitBreaker") .run( () -> { // Actual business logic, such as remote call return (userId); }, throwable -> { // downgrade processing return "Fallback User Info"; } ); } }
Step 4: Define the Fallback method
passfallbackMethod
The attribute specifies the downgrade method:
@CircuitBreaker(name = "userService", fallbackMethod = "getUserFallback") public User getUser(String userId) { // Call remote service} // The method signature must be consistent with the original method, and finally add the Throwable parameterprivate User getUserFallback(String userId, Throwable t) { return new User("fallback-user", "Service Unavailable"); }
Step 5: Configure global default values
Customize global default configuration:
@Bean public CircuitBreakerConfigCustomizer defaultConfig() { return config -> config .failureRateThreshold(60) .waitDurationInOpenState((10)); }
Advanced configuration
1. Combined with Retry mechanism
Try to try again before the circuit breaker:
resilience4j: retry: configs: default: maxAttempts: 3 waitDuration: 500ms
2. Combination of current limiting and fuse
useBulkhead
Restrict concurrent calls:
@Bulkhead(name = "userService", type = ) @CircuitBreaker(name = "userService") public User getUser(String userId) { ... }
Summarize
Through Spring Cloud CircuitBreaker, we can effectively improve the flexibility of microservice architecture. The key is:
Correctly configure the fuse parameters
Design a reasonable downgrade strategy
In combination with the monitoring system, timely discover problems
This is the end of this article about the detailed steps of SpringCloud using CircuitBreaker to implement fuses. For more related SpringCloud CircuitBreaker content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!