Skip to main content

dawdler-circuit-breaker

Module Introduction​

A circuit breaker implemented with a sliding time window, supporting circuit breaker configuration and fallback.

1. Add the dependency to the pom of the web side​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-circuit-breaker</artifactId>

2. Define a circuit breaker on methods of the service interface layer​

Methods annotated with @CircuitBreaker have the circuit breaker enabled.

Example:

@Service("user-service")
public interface UserService {

@CircuitBreaker
Map<String, Object> selectUserList(int pageOn)throws Exception;

}

3. Service fallback​

@CircuitBreaker has a fallbackMethod property; fallbackMethod is the implementation of a method in the interface.

The fallback method must be a default method or a static method in the interface, and its parameters and return value must be the same as the original method. After the circuit breaker opens, the fallback is executed locally on the client without initiating a remote call, and the method body should not call other methods of the interface either.

The circuit breaker check is performed before acquiring a connection, covering connection pool acquisition, load balancing, session waiting, and the actual RPC call. Connection preparation failures are counted according to the same exception classification rules, and multiple connection failovers within a single call are settled only once. When the breaker is OPEN or a call is rejected because a half-open probe is occupied, no connection is acquired, no session is waited for, and the fallback is executed directly; if no fallback is configured, a CircuitBreakerOpenException is thrown. A failure of a call that was permitted to execute still throws the exception as-is and does not immediately switch to the fallback. An asynchronous call that fails before being sent is settled immediately; after it is sent successfully, the statistics wait for the final result of the future.

Example:

@CircuitBreaker(fallbackMethod = "selectUserListFallback")
Map<String, Object> selectUserList(int pageOn)throws Exception;

default Map<String, Object> selectUserListFallback(int pageOn)throws Exception{
Map<String, Object> result = new HashMap<>();
return result;
}

static methods are also supported:

@CircuitBreaker(fallbackMethod = "selectUserListFallback")
Map<String, Object> selectUserList(int pageOn)throws Exception;

static Map<String, Object> selectUserListFallback(int pageOn)throws Exception{
Map<String, Object> result = new HashMap<>();
return result;
}

4. Exception classification (counted in / ignored for breaker failures)​

@CircuitBreaker supports two properties, recordExceptions and ignoreExceptions, used to control which exceptions are counted in breaker failure statistics.

  • recordExceptions: exception types (including subclasses) counted as breaker failures
  • ignoreExceptions: exception types (including subclasses) ignored and not counted as breaker failures; takes precedence over recordExceptions

When neither property is configured, the default policy applies: Error (such as OutOfMemoryError, StackOverflowError) as well as InterruptedException and CancellationException are not counted as failures; all other exceptions are counted as failures.

Matching searches along the cause chain, so remote exceptions wrapped by the RPC layer (e.g., an IOException wrapped in DawdlerOperateException) can also be matched correctly.

Example (exception types can be customized according to the actual business; UserBizException in the example below is a user-defined business exception):

@CircuitBreaker(
recordExceptions = {IOException.class, TimeoutException.class},
ignoreExceptions = {UserBizException.class}
)
Map<String, Object> selectUserList(int pageOn)throws Exception;

In the example above, only IOException and its subclasses, and TimeoutException and its subclasses, are counted as breaker failures; UserBizException and its subclasses (even if wrapped in the cause chain) are ignored and do not affect breaker statistics; other unconfigured exceptions are handled by the default policy.

Typical use cases: business validation exceptions belong to normal business flow and should not trigger the breaker, so configure them in ignoreExceptions; only infrastructure exceptions such as network IO and timeouts should be counted in breaker statistics, so configure them in recordExceptions.

5. CircuitBreaker property descriptions​

public @interface CircuitBreaker {

/**
* @return String
* identifier key; when the default "" is used, the combination of servicePath+serviceName+serviceMethod is used
*/
String breakerKey() default "";

/**
* @return int
* statistics duration intervalInMs/windowsCount; an integer is recommended; defaults to 3000, in milliseconds.
*/
int intervalInMs() default 3000;

/**
* @return int
* window size
*/
int windowsCount() default 2;

/**
* @return int
* After the circuit breaker opens, all requests fail directly. When the circuit breaker is open, after a period of time a single request is allowed through;
* if it succeeds, the circuit breaker is closed. This configuration specifies that period of time; the default is
* 5000, in milliseconds.
*/
int sleepWindowInMilliseconds() default 5000;

/**
* @return int
* The minimum number of requests within the window time that enables the circuit breaker feature; defaults to 5.
*/

int requestVolumeThreshold() default 5;

/**
* @return double
* error percentage; defaults to 40%. When the error rate reaches 40% the breaker is triggered (greater than requestVolumeThreshold)
*/
double errorThresholdPercentage() default 0.4;

/**
* @return String
* method executed after the breaker trips; its parameters and return value are the same as those of the executed method
*/
String fallbackMethod() default "";

/**
* @return Class<? extends Throwable>[]
* exception types (including subclasses) counted as breaker failures; matching searches along the cause chain; when empty, the default policy applies:
* all exceptions except Error and InterruptedException/CancellationException are counted as failures
*/
Class<? extends Throwable>[] recordExceptions() default {};

/**
* @return Class<? extends Throwable>[]
* exception types (including subclasses) ignored and not counted as breaker failures; matching searches along the cause chain; takes precedence over recordExceptions;
* e.g., configure here the business validation exceptions that should not trigger the breaker
*/
Class<? extends Throwable>[] ignoreExceptions() default {};

}