Package com.guinetik.rr.http
Class CircuitBreakerClient
- java.lang.Object
-
- com.guinetik.rr.http.CircuitBreakerClient
-
- All Implemented Interfaces:
RocketClient
public class CircuitBreakerClient extends Object implements RocketClient
Decorator that adds circuit breaker resilience pattern to anyRocketClient.The circuit breaker pattern prevents cascading failures by failing fast when a downstream service appears unhealthy. This gives the service time to recover without being overwhelmed by requests that are likely to fail.
Circuit Breaker States
- CLOSED - Normal operation, requests pass through
- OPEN - Circuit is open, requests fail fast with
CircuitBreakerOpenException - HALF_OPEN - Testing if service recovered, next request determines state
Basic Usage
// Wrap any RocketClient with circuit breaker RocketClient baseClient = new DefaultHttpClient("https://api.example.com"); CircuitBreakerClient client = new CircuitBreakerClient(baseClient); try { User user = client.execute(request); } catch (CircuitBreakerOpenException e) { System.out.println("Service unavailable, retry after: " + e.getEstimatedMillisUntilReset() + "ms"); }Custom Configuration
// Circuit opens after 3 failures, resets after 60 seconds CircuitBreakerClient client = new CircuitBreakerClient( baseClient, 3, // failure threshold 60000 // reset timeout in ms );Via RocketClientFactory
RocketClient client = RocketClientFactory.builder("https://api.example.com") .withCircuitBreaker(5, 30000) .build();- Since:
- 1.0.0
- Author:
- guinetik <guinetik@gmail.com>
- See Also:
RocketClient,CircuitBreakerOpenException,RocketClientFactory
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classCircuitBreakerClient.FailurePolicyStrategy for differentiating between failuresstatic classCircuitBreakerClient.StateCircuit breaker state
-
Constructor Summary
Constructors Constructor Description CircuitBreakerClient(RocketClient delegate)Creates a circuit breaker with default settingsCircuitBreakerClient(RocketClient delegate, int failureThreshold, long resetTimeoutMs)Creates a circuit breaker with custom threshold and timeoutCircuitBreakerClient(RocketClient delegate, int failureThreshold, long resetTimeoutMs, long failureDecayTimeMs, CircuitBreakerClient.FailurePolicy failurePolicy, Predicate<RocketRestException> failurePredicate)Creates a fully customized circuit breaker
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidconfigureSsl(SSLContext sslContext)Sets the SSL context to be used for HTTPS requests.<Req,Res>
Resexecute(RequestSpec<Req,Res> requestSpec)Executes an HTTP request based on the provided request specification.intgetFailureCount()Gets current failure countMap<String,Object>getMetrics()Gets circuit breaker metricsCircuitBreakerClient.StategetState()Gets current circuit breaker state<Req,Res>
booleanperformHealthCheck(RequestSpec<Req,Res> healthCheckRequest)Performs a health check by trying to execute the given request.voidresetCircuit()Manually resets the circuit to closed state.voidsetBaseUrl(String baseUrl)
-
-
-
Constructor Detail
-
CircuitBreakerClient
public CircuitBreakerClient(RocketClient delegate)
Creates a circuit breaker with default settings- Parameters:
delegate- The underlying client implementation
-
CircuitBreakerClient
public CircuitBreakerClient(RocketClient delegate, int failureThreshold, long resetTimeoutMs)
Creates a circuit breaker with custom threshold and timeout- Parameters:
delegate- The underlying client implementationfailureThreshold- Number of failures before opening circuitresetTimeoutMs- Time in milliseconds before trying to close circuit
-
CircuitBreakerClient
public CircuitBreakerClient(RocketClient delegate, int failureThreshold, long resetTimeoutMs, long failureDecayTimeMs, CircuitBreakerClient.FailurePolicy failurePolicy, Predicate<RocketRestException> failurePredicate)
Creates a fully customized circuit breaker- Parameters:
delegate- The underlying client implementation (must not be null)failureThreshold- Number of failures before opening circuitresetTimeoutMs- Time in milliseconds before trying to close circuitfailureDecayTimeMs- Time after which failure count starts to decayfailurePolicy- Strategy to determine what counts as a failurefailurePredicate- Custom predicate if policy is CUSTOM- Throws:
NullPointerException- if delegate is nullIllegalArgumentException- if failureThreshold is less than 1 or timeouts are negative
-
-
Method Detail
-
execute
public <Req,Res> Res execute(RequestSpec<Req,Res> requestSpec) throws RocketRestException
Description copied from interface:RocketClientExecutes an HTTP request based on the provided request specification.- Specified by:
executein interfaceRocketClient- Type Parameters:
Req- The type of the request body.Res- The type of the response.- Parameters:
requestSpec- The specification of the request to be executed.- Returns:
- The response object.
- Throws:
RocketRestException- If an error occurs during the request execution.
-
performHealthCheck
public <Req,Res> boolean performHealthCheck(RequestSpec<Req,Res> healthCheckRequest)
Performs a health check by trying to execute the given request. This can be used to manually test if the service is healthy.Note: This method bypasses the normal circuit breaker flow and directly executes the request against the delegate. It's intended for external health monitoring systems.
- Type Parameters:
Req- Request typeRes- Response type- Parameters:
healthCheckRequest- The request to use as a health check- Returns:
- true if the service is healthy
-
resetCircuit
public void resetCircuit()
Manually resets the circuit to closed state. This also resets all internal state including failure counts and test flags.
-
getState
public CircuitBreakerClient.State getState()
Gets current circuit breaker state- Returns:
- Current state (OPEN, CLOSED, HALF_OPEN)
-
getFailureCount
public int getFailureCount()
Gets current failure count- Returns:
- Current failure count
-
getMetrics
public Map<String,Object> getMetrics()
Gets circuit breaker metrics- Returns:
- Map of metric name to value
-
configureSsl
public void configureSsl(SSLContext sslContext)
Description copied from interface:RocketClientSets the SSL context to be used for HTTPS requests.- Specified by:
configureSslin interfaceRocketClient- Parameters:
sslContext- The SSL context to use.
-
setBaseUrl
public void setBaseUrl(String baseUrl)
- Specified by:
setBaseUrlin interfaceRocketClient
-
-