Search in sources :

Example 16 with CircuitBreaker

use of io.github.resilience4j.circuitbreaker.CircuitBreaker in project resilience4j by resilience4j.

the class DecoratorsTest method testDecorateCompletionStage.

@Test
public void testDecorateCompletionStage() throws ExecutionException, InterruptedException {
    // Given the HelloWorldService returns Hello world
    given(helloWorldService.returnHelloWorld()).willReturn("Hello world");
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    Supplier<CompletionStage<String>> completionStageSupplier = () -> CompletableFuture.supplyAsync(helloWorldService::returnHelloWorld);
    CompletionStage<String> completionStage = Decorators.ofCompletionStage(completionStageSupplier).withCircuitBreaker(circuitBreaker).withRetry(AsyncRetry.ofDefaults("id"), Executors.newSingleThreadScheduledExecutor()).withBulkhead(Bulkhead.ofDefaults("testName")).get();
    String value = completionStage.toCompletableFuture().get();
    assertThat(value).isEqualTo("Hello world");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    // Then the helloWorldService should be invoked 1 time
    BDDMockito.then(helloWorldService).should(times(1)).returnHelloWorld();
}
Also used : CircuitBreaker(io.github.resilience4j.circuitbreaker.CircuitBreaker) CompletionStage(java.util.concurrent.CompletionStage) Test(org.junit.Test)

Example 17 with CircuitBreaker

use of io.github.resilience4j.circuitbreaker.CircuitBreaker in project resilience4j by resilience4j.

the class DecoratorsTest method testDecorateRunnable.

@Test
public void testDecorateRunnable() {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    Runnable decoratedRunnable = Decorators.ofRunnable(() -> helloWorldService.sayHelloWorld()).withCircuitBreaker(circuitBreaker).withRetry(Retry.ofDefaults("id")).withRateLimiter(RateLimiter.ofDefaults("testName")).withBulkhead(Bulkhead.ofDefaults("testName")).decorate();
    decoratedRunnable.run();
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    // Then the helloWorldService should be invoked 1 time
    BDDMockito.then(helloWorldService).should(times(1)).sayHelloWorld();
}
Also used : CircuitBreaker(io.github.resilience4j.circuitbreaker.CircuitBreaker) CheckedRunnable(io.vavr.CheckedRunnable) Test(org.junit.Test)

Example 18 with CircuitBreaker

use of io.github.resilience4j.circuitbreaker.CircuitBreaker in project resilience4j by resilience4j.

the class DecoratorsTest method testDecorateFunction.

@Test
public void testDecorateFunction() {
    // Given the HelloWorldService returns Hello world
    given(helloWorldService.returnHelloWorldWithName("Name")).willReturn("Hello world Name");
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    Function<String, String> decoratedFunction = Decorators.ofFunction(helloWorldService::returnHelloWorldWithName).withCircuitBreaker(circuitBreaker).withRetry(Retry.ofDefaults("id")).withRateLimiter(RateLimiter.ofDefaults("testName")).withBulkhead(Bulkhead.ofDefaults("testName")).decorate();
    String result = decoratedFunction.apply("Name");
    assertThat(result).isEqualTo("Hello world Name");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
}
Also used : CircuitBreaker(io.github.resilience4j.circuitbreaker.CircuitBreaker) Test(org.junit.Test)

Example 19 with CircuitBreaker

use of io.github.resilience4j.circuitbreaker.CircuitBreaker in project resilience4j by resilience4j.

the class DecoratorsTest method testExecuteConsumer.

@Test
public void testExecuteConsumer() throws ExecutionException, InterruptedException {
    // Given the HelloWorldService returns Hello world
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    Decorators.ofConsumer((String input) -> helloWorldService.sayHelloWorldWithName(input)).withCircuitBreaker(circuitBreaker).withBulkhead(Bulkhead.ofDefaults("testName")).withRateLimiter(RateLimiter.ofDefaults("testName")).accept("test");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    // Then the helloWorldService should be invoked 1 time
    BDDMockito.then(helloWorldService).should(times(1)).sayHelloWorldWithName("test");
}
Also used : CircuitBreaker(io.github.resilience4j.circuitbreaker.CircuitBreaker) Test(org.junit.Test)

Example 20 with CircuitBreaker

use of io.github.resilience4j.circuitbreaker.CircuitBreaker in project resilience4j by resilience4j.

the class CircuitBreakerAutoTransitionStateMachineTest method setUp.

@Before
public void setUp() {
    CircuitBreakerConfig circuitBreakerConfigGroupA = CircuitBreakerConfig.custom().failureRateThreshold(50).ringBufferSizeInClosedState(5).ringBufferSizeInHalfOpenState(3).enableAutomaticTransitionFromOpenToHalfOpen().waitDurationInOpenState(Duration.ofSeconds(2)).recordFailure(error -> !(error instanceof NumberFormatException)).build();
    CircuitBreakerConfig circuitBreakerConfigGroupB = CircuitBreakerConfig.custom().failureRateThreshold(50).ringBufferSizeInClosedState(5).ringBufferSizeInHalfOpenState(3).enableAutomaticTransitionFromOpenToHalfOpen().waitDurationInOpenState(Duration.ofSeconds(1)).recordFailure(error -> !(error instanceof NumberFormatException)).build();
    // Instantiate multiple circuit breakers in two groups, A & B
    for (int i = 0; i < TOTAL_NUMBER_CIRCUIT_BREAKERS; i++) {
        stateTransitionFromOpenToHalfOpen.put(i, 0);
        // On state transition from OPEN to HALF_OPEN, increment a count
        int finalI = i;
        EventConsumer<CircuitBreakerOnStateTransitionEvent> eventConsumer = transition -> {
            if (transition.getStateTransition().getFromState().equals(CircuitBreaker.State.OPEN) && transition.getStateTransition().getToState().equals(CircuitBreaker.State.HALF_OPEN)) {
                Integer currentCount = stateTransitionFromOpenToHalfOpen.get(finalI);
                stateTransitionFromOpenToHalfOpen.put(finalI, currentCount + 1);
            }
        };
        CircuitBreaker circuitBreaker;
        if (i < TOTAL_NUMBER_CIRCUIT_BREAKERS / 2) {
            circuitBreaker = new CircuitBreakerStateMachine("testNameA" + i, circuitBreakerConfigGroupA);
            circuitBreaker.getEventPublisher().onStateTransition(eventConsumer);
            circuitBreakersGroupA.add(circuitBreaker);
        } else {
            circuitBreaker = new CircuitBreakerStateMachine("testNameB" + i, circuitBreakerConfigGroupB);
            circuitBreaker.getEventPublisher().onStateTransition(eventConsumer);
            circuitBreakersGroupB.add(circuitBreaker);
        }
    }
}
Also used : CircuitBreaker(io.github.resilience4j.circuitbreaker.CircuitBreaker) CircuitBreakerOnStateTransitionEvent(io.github.resilience4j.circuitbreaker.event.CircuitBreakerOnStateTransitionEvent) Test(org.junit.Test) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) CircuitBreakerConfig(io.github.resilience4j.circuitbreaker.CircuitBreakerConfig) EventConsumer(io.github.resilience4j.core.EventConsumer) List(java.util.List) Duration(java.time.Duration) Map(java.util.Map) Thread.sleep(java.lang.Thread.sleep) BDDAssertions.assertThat(org.assertj.core.api.BDDAssertions.assertThat) Before(org.junit.Before) CircuitBreaker(io.github.resilience4j.circuitbreaker.CircuitBreaker) CircuitBreakerOnStateTransitionEvent(io.github.resilience4j.circuitbreaker.event.CircuitBreakerOnStateTransitionEvent) CircuitBreakerConfig(io.github.resilience4j.circuitbreaker.CircuitBreakerConfig) Before(org.junit.Before)

Aggregations

CircuitBreaker (io.github.resilience4j.circuitbreaker.CircuitBreaker)26 Test (org.junit.Test)19 CircuitBreakerRegistry (io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry)9 CircuitBreakerConfig (io.github.resilience4j.circuitbreaker.CircuitBreakerConfig)6 CircuitBreakerEvent (io.github.resilience4j.circuitbreaker.event.CircuitBreakerEvent)6 CircuitBreakerOpenException (io.github.resilience4j.circuitbreaker.CircuitBreakerOpenException)3 InMemoryCircuitBreakerRegistry (io.github.resilience4j.circuitbreaker.internal.InMemoryCircuitBreakerRegistry)3 Type (io.github.resilience4j.circuitbreaker.event.CircuitBreakerEvent.Type)2 CircularEventConsumer (io.github.resilience4j.consumer.CircularEventConsumer)2 EventConsumerRegistry (io.github.resilience4j.consumer.EventConsumerRegistry)2 CollectorRegistry (io.prometheus.client.CollectorRegistry)2 CheckedRunnable (io.vavr.CheckedRunnable)2 Tuple (io.vavr.Tuple)2 HashMap (io.vavr.collection.HashMap)2 HashSet (io.vavr.collection.HashSet)2 Map (io.vavr.collection.Map)2 Seq (io.vavr.collection.Seq)2 Duration (java.time.Duration)2 ArrayList (java.util.ArrayList)2 Comparator (java.util.Comparator)2