Class CircuitBreakerClient

  • All Implemented Interfaces:
    RocketClient

    public class CircuitBreakerClient
    extends Object
    implements RocketClient
    Decorator that adds circuit breaker resilience pattern to any RocketClient.

    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
    • 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 implementation
        failureThreshold - Number of failures before opening circuit
        resetTimeoutMs - 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 circuit
        resetTimeoutMs - Time in milliseconds before trying to close circuit
        failureDecayTimeMs - Time after which failure count starts to decay
        failurePolicy - Strategy to determine what counts as a failure
        failurePredicate - Custom predicate if policy is CUSTOM
        Throws:
        NullPointerException - if delegate is null
        IllegalArgumentException - 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: RocketClient
        Executes an HTTP request based on the provided request specification.
        Specified by:
        execute in interface RocketClient
        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 type
        Res - 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: RocketClient
        Sets the SSL context to be used for HTTPS requests.
        Specified by:
        configureSsl in interface RocketClient
        Parameters:
        sslContext - The SSL context to use.