Java Code Examples for io.github.resilience4j.circuitbreaker.CircuitBreaker#ofDefaults()

The following examples show how to use io.github.resilience4j.circuitbreaker.CircuitBreaker#ofDefaults() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CircularEventConsumerTest.java    From resilience4j with Apache License 2.0 7 votes vote down vote up
@Test
public void shouldNotBufferEvents() {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
    CircularEventConsumer<CircuitBreakerEvent> ringBuffer = new CircularEventConsumer<>(2);
    assertThat(ringBuffer.getBufferedEvents()).isEmpty();

    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla"));
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla"));
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla"));
    //Subscription is too late
    circuitBreaker.getEventPublisher().onEvent(ringBuffer);

    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(3);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(3);
    //Because Subscription was too late
    assertThat(ringBuffer.getBufferedEvents()).hasSize(0);
}
 
Example 2
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCompletionStageWithCallNotPermittedExceptionFallback() throws ExecutionException, InterruptedException {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    circuitBreaker.transitionToOpenState();
    ThreadPoolBulkhead bulkhead = ThreadPoolBulkhead.ofDefaults("helloBackend");
    CompletionStage<String> completionStage = Decorators
        .ofSupplier(() -> helloWorldService.returnHelloWorld())
        .withThreadPoolBulkhead(bulkhead)
        .withCircuitBreaker(circuitBreaker)
        .withFallback(CallNotPermittedException.class, (e) -> "Fallback")
        .get();

    String result = completionStage.toCompletableFuture().get();

    assertThat(result).isEqualTo("Fallback");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfNotPermittedCalls()).isEqualTo(1);
}
 
Example 3
Source File: CircularEventConsumerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBufferErrorEvents() {
    // tag::shouldBufferEvents[]
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
    CircularEventConsumer<CircuitBreakerEvent> ringBuffer = new CircularEventConsumer<>(2);
    circuitBreaker.getEventPublisher().onEvent(ringBuffer);
    // end::shouldBufferEvents[]
    assertThat(ringBuffer.getBufferedEvents()).isEmpty();

    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla"));
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla"));
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla"));

    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(3);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(3);
    //Because capacity is 2
    assertThat(ringBuffer.getBufferedEvents()).hasSize(2);
}
 
Example 4
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecoratorBuilderWithRetry() {
    given(helloWorldService.returnHelloWorld()).willThrow(new RuntimeException("BAM!"));
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    Supplier<String> decoratedSupplier = Decorators
        .ofSupplier(() -> helloWorldService.returnHelloWorld())
        .withCircuitBreaker(circuitBreaker)
        .withRetry(Retry.ofDefaults("id"))
        .withBulkhead(Bulkhead.ofDefaults("testName"))
        .decorate();

    Try.of(decoratedSupplier::get);

    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(3);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(3);
    then(helloWorldService).should(times(3)).returnHelloWorld();
}
 
Example 5
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCheckedFunction() throws IOException {
    given(helloWorldService.returnHelloWorldWithNameWithException("Name"))
        .willReturn("Hello world Name");
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    CheckedFunction1<String, String> decoratedFunction = Decorators
        .ofCheckedFunction(helloWorldService::returnHelloWorldWithNameWithException)
        .withCircuitBreaker(circuitBreaker)
        .withRetry(Retry.ofDefaults("id"))
        .withRateLimiter(RateLimiter.ofDefaults("testName"))
        .withBulkhead(Bulkhead.ofDefaults("testName"))
        .decorate();

    String result = Try.of(() -> decoratedFunction.apply("Name")).get();

    assertThat(result).isEqualTo("Hello world Name");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
}
 
Example 6
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateFunction() {
    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);
}
 
Example 7
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteConsumer() {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    Decorators.DecorateConsumer<String> decoratedConsumer =
        Decorators.ofConsumer((String input) -> helloWorldService
            .sayHelloWorldWithName(input))
            .withCircuitBreaker(circuitBreaker)
            .withBulkhead(Bulkhead.ofDefaults("testName"))
            .withRateLimiter(RateLimiter.ofDefaults("testName"));

    decoratedConsumer.accept("test");

    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    then(helloWorldService).should(times(1)).sayHelloWorldWithName("test");
}
 
Example 8
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCompletionStage() throws ExecutionException, InterruptedException {
    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(Retry.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(helloWorldService).should(times(1)).returnHelloWorld();
}
 
Example 9
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCheckedRunnable() throws IOException {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    CheckedRunnable decoratedRunnable = Decorators
        .ofCheckedRunnable(() -> helloWorldService.sayHelloWorldWithException())
        .withCircuitBreaker(circuitBreaker)
        .withRetry(Retry.ofDefaults("id"))
        .withRateLimiter(RateLimiter.ofDefaults("testName"))
        .withBulkhead(Bulkhead.ofDefaults("testName"))
        .decorate();

    Try.run(decoratedRunnable);

    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    then(helloWorldService).should(times(1)).sayHelloWorldWithException();
}
 
Example 10
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@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(helloWorldService).should(times(1)).sayHelloWorld();
}
 
Example 11
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCompletionStageWithTimeoutExceptionFallback() throws ExecutionException, InterruptedException {
    TimeLimiter timeLimiter = TimeLimiter.of("helloBackend", TimeLimiterConfig.custom()
        .timeoutDuration(Duration.ofMillis(100)).build());
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    ThreadPoolBulkhead bulkhead = ThreadPoolBulkhead.ofDefaults("helloBackend");
    CompletionStage<String> completionStage = Decorators
        .ofCallable(() -> {
            Thread.sleep(1000);
            return "Bla";
        })
        .withThreadPoolBulkhead(bulkhead)
        .withTimeLimiter(timeLimiter, Executors.newSingleThreadScheduledExecutor())
        .withCircuitBreaker(circuitBreaker)
        .withFallback(TimeoutException.class, (e) -> "Fallback")
        .get();

    String result = completionStage.toCompletableFuture().get();

    assertThat(result).isEqualTo("Fallback");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
}
 
Example 12
Source File: FeignDecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithCircuitBreaker() throws Throwable {
    final CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");
    final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    final FeignDecorators testSubject = FeignDecorators.builder()
        .withCircuitBreaker(circuitBreaker).build();

    final Object result = testSubject.decorate(args -> args[0], null, null, null)
        .apply(new Object[]{"test01"});

    assertThat(result)
        .describedAs("Returned result is correct")
        .isEqualTo("test01");
    assertThat(metrics.getNumberOfSuccessfulCalls())
        .describedAs("Successful Calls")
        .isEqualTo(1);
}
 
Example 13
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCallableWithFallback() throws Throwable {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    circuitBreaker.transitionToOpenState();

    Callable<String> callable = Decorators
        .ofCallable(() -> helloWorldService.returnHelloWorldWithException())
        .withCircuitBreaker(circuitBreaker)
        .withFallback(CallNotPermittedException.class, e -> "Fallback")
        .decorate();

    String result = callable.call();

    assertThat(result).isEqualTo("Fallback");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfNotPermittedCalls()).isEqualTo(1);
    then(helloWorldService).should(never()).returnHelloWorld();
}
 
Example 14
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCheckedSupplierWithFallback() throws Throwable {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    circuitBreaker.transitionToOpenState();

    CheckedFunction0<String> checkedSupplier = Decorators
        .ofCheckedSupplier(() -> helloWorldService.returnHelloWorldWithException())
        .withCircuitBreaker(circuitBreaker)
        .withFallback(CallNotPermittedException.class, e -> "Fallback")
        .decorate();

    String result = checkedSupplier.apply();

    assertThat(result).isEqualTo("Fallback");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfNotPermittedCalls()).isEqualTo(1);
    then(helloWorldService).should(never()).returnHelloWorld();
}
 
Example 15
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCheckedSupplier() throws IOException {
    given(helloWorldService.returnHelloWorldWithException()).willReturn("Hello world");
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    CheckedFunction0<String> decoratedSupplier = Decorators
        .ofCheckedSupplier(() -> helloWorldService.returnHelloWorldWithException())
        .withCircuitBreaker(circuitBreaker)
        .withRetry(Retry.ofDefaults("id"))
        .withRateLimiter(RateLimiter.ofDefaults("testName"))
        .withBulkhead(Bulkhead.ofDefaults("testName"))
        .decorate();

    String result = Try.of(decoratedSupplier).get();

    assertThat(result).isEqualTo("Hello world");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    then(helloWorldService).should(times(1)).returnHelloWorldWithException();
}
 
Example 16
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateSupplier() {
    given(helloWorldService.returnHelloWorld()).willReturn("Hello world");
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    Supplier<String> decoratedSupplier = Decorators
        .ofSupplier(() -> helloWorldService.returnHelloWorld())
        .withCircuitBreaker(circuitBreaker)
        .withRetry(Retry.ofDefaults("id"))
        .withRateLimiter(RateLimiter.ofDefaults("testName"))
        .withBulkhead(Bulkhead.ofDefaults("testName"))
        .decorate();

    String result = decoratedSupplier.get();

    assertThat(result).isEqualTo("Hello world");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    then(helloWorldService).should(times(1)).returnHelloWorld();
}
 
Example 17
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrowTimeoutException() {
    TimeLimiter timeLimiter = TimeLimiter.of("helloBackend", TimeLimiterConfig.custom()
        .timeoutDuration(Duration.ofMillis(100)).build());
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    ThreadPoolBulkhead bulkhead = ThreadPoolBulkhead.ofDefaults("helloBackend");
    CompletionStage<String> completionStage = Decorators
        .ofCallable(() -> {
            Thread.sleep(1000);
            return "Bla";
        })
        .withThreadPoolBulkhead(bulkhead)
        .withTimeLimiter(timeLimiter, Executors.newSingleThreadScheduledExecutor())
        .withCircuitBreaker(circuitBreaker)
        .get();

    assertThatThrownBy(() -> completionStage.toCompletableFuture().get())
        .hasCauseInstanceOf(TimeoutException.class);

    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
}
 
Example 18
Source File: RxJava2CircuitBreakerAspectExtTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testReactorTypes() throws Throwable {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");

    when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
    assertThat(rxJava2CircuitBreakerAspectExt
        .handle(proceedingJoinPoint, circuitBreaker, "testMethod")).isNotNull();

    when(proceedingJoinPoint.proceed()).thenReturn(Flowable.just("Test"));
    assertThat(rxJava2CircuitBreakerAspectExt
        .handle(proceedingJoinPoint, circuitBreaker, "testMethod")).isNotNull();
}
 
Example 19
Source File: ReactorCircuitBreakerAspectExtTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testReactorTypes() throws Throwable {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");

    when(proceedingJoinPoint.proceed()).thenReturn(Mono.just("Test"));
    assertThat(reactorCircuitBreakerAspectExt
        .handle(proceedingJoinPoint, circuitBreaker, "testMethod")).isNotNull();

    when(proceedingJoinPoint.proceed()).thenReturn(Flux.just("Test"));
    assertThat(reactorCircuitBreakerAspectExt
        .handle(proceedingJoinPoint, circuitBreaker, "testMethod")).isNotNull();
}
 
Example 20
Source File: CircuitBreakerSubscriberWhiteboxVerification.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
@Override
public Subscriber<Integer> createSubscriber(WhiteboxSubscriberProbe<Integer> probe) {
    return new CircuitBreakerSubscriber<Integer>(CircuitBreaker.ofDefaults("verification"),
        MonoProcessor.create(), false) {

        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            super.hookOnSubscribe(subscription);

            // register a successful Subscription, and create a Puppet,
            // for the WhiteboxVerification to be able to drive its tests:
            probe.registerOnSubscribe(new SubscriberPuppet() {

                @Override
                public void triggerRequest(long elements) {
                    subscription.request(elements);
                }

                @Override
                public void signalCancel() {
                    subscription.cancel();
                }
            });
        }

        @Override
        public void hookOnNext(Integer integer) {
            super.hookOnNext(integer);
            probe.registerOnNext(integer);
        }

        @Override
        public void hookOnError(Throwable t) {
            super.hookOnError(t);
            probe.registerOnError(t);
        }

        @Override
        public void hookOnComplete() {
            super.hookOnComplete();
            probe.registerOnComplete();
        }
    };
}