Java Code Examples for io.github.resilience4j.circuitbreaker.CircuitBreaker#Metrics
The following examples show how to use
io.github.resilience4j.circuitbreaker.CircuitBreaker#Metrics .
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 |
@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: RetrofitCircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void decorateUnsuccessfulCall() throws Exception { stubFor(get(urlPathEqualTo("/greeting")) .willReturn(aResponse() .withStatus(500) .withHeader("Content-Type", "text/plain"))); final Response<String> response = service.greeting().execute(); assertThat(response.code()) .describedAs("Response code") .isEqualTo(500); final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1); }
Example 3
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 4
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 5
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 6
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 7
Source File: RetrofitCircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldDelegateToOtherAdapter() { String body = "this is from rxjava"; stubFor(get(urlPathEqualTo("/delegated")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/plain") .withBody(body))); RetrofitService service = new Retrofit.Builder() .addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create()) .baseUrl(wireMockRule.baseUrl()) .client(client) .build() .create(RetrofitService.class); String resultBody = service.delegated().blockingGet(); assertThat(resultBody).isEqualTo(body); verify(1, getRequestedFor(urlPathEqualTo("/delegated"))); final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1); }
Example 8
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void testDecorateSupplierWithFallback() { CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend"); circuitBreaker.transitionToOpenState(); Supplier<String> decoratedSupplier = Decorators .ofSupplier(() -> helloWorldService.returnHelloWorld()) .withCircuitBreaker(circuitBreaker) .withFallback(asList(IOException.class, CallNotPermittedException.class), (e) -> "Fallback") .decorate(); String result = decoratedSupplier.get(); assertThat(result).isEqualTo("Fallback"); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfNotPermittedCalls()).isEqualTo(1); then(helloWorldService).should(never()).returnHelloWorld(); }
Example 9
Source File: RetrofitCircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void decorateUnsuccessfulEnqueuedCall() throws Throwable { stubFor(get(urlPathEqualTo("/greeting")) .willReturn(aResponse() .withStatus(500) .withHeader("Content-Type", "text/plain"))); final Response<String> response = EnqueueDecorator.enqueue(service.greeting()); assertThat(response.code()) .describedAs("Response code") .isEqualTo(500); final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1); }
Example 10
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void testDecorateSupplierWithThreadPoolBulkhead() throws ExecutionException, InterruptedException { given(helloWorldService.returnHelloWorld()).willReturn("Hello world"); CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend"); CompletableFuture<String> future = Decorators .ofSupplier(() -> helloWorldService.returnHelloWorld()) .withThreadPoolBulkhead(ThreadPoolBulkhead.ofDefaults("helloBackend")) .withTimeLimiter(TimeLimiter.ofDefaults(), Executors.newSingleThreadScheduledExecutor()) .withCircuitBreaker(circuitBreaker) .get().toCompletableFuture(); String result = future.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 11
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 12
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 13
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 14
Source File: Resilience4jFeignCircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void testFailedCall() throws Exception { final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); boolean exceptionThrown = false; setupStub(400); try { testService.greeting(); } catch (final FeignException ex) { exceptionThrown = true; } assertThat(exceptionThrown) .describedAs("FeignException thrown") .isTrue(); assertThat(metrics.getNumberOfFailedCalls()) .describedAs("Successful Calls") .isEqualTo(1); }
Example 15
Source File: FeignDecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 16
Source File: CircuitBreakerMetricsDTO.java From resilience4j with Apache License 2.0 | 5 votes |
public CircuitBreakerMetricsDTO(CircuitBreaker.Metrics metrics) { this.failureRate = metrics.getFailureRate(); this.numberOfBufferedCalls = metrics.getNumberOfBufferedCalls(); this.numberOfFailedCalls = metrics.getNumberOfFailedCalls(); this.numberOfNotPermittedCalls = metrics.getNumberOfNotPermittedCalls(); this.numberOfSuccessfulCalls = metrics.getNumberOfSuccessfulCalls(); }
Example 17
Source File: CircuitBreakersHealthIndicatorTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void testHealthStatus() { CircuitBreaker openCircuitBreaker = mock(CircuitBreaker.class); CircuitBreaker halfOpenCircuitBreaker = mock(CircuitBreaker.class); CircuitBreaker closeCircuitBreaker = mock(CircuitBreaker.class); Map<CircuitBreaker.State, CircuitBreaker> expectedStateToCircuitBreaker = new HashMap<>(); expectedStateToCircuitBreaker.put(OPEN, openCircuitBreaker); expectedStateToCircuitBreaker.put(HALF_OPEN, halfOpenCircuitBreaker); expectedStateToCircuitBreaker.put(CLOSED, closeCircuitBreaker); CircuitBreakerConfigurationProperties.InstanceProperties instanceProperties = mock(CircuitBreakerConfigurationProperties.InstanceProperties.class); CircuitBreakerConfigurationProperties circuitBreakerProperties = mock( CircuitBreakerConfigurationProperties.class); // given CircuitBreakerRegistry registry = mock(CircuitBreakerRegistry.class); CircuitBreakerConfig config = mock(CircuitBreakerConfig.class); CircuitBreaker.Metrics metrics = mock(CircuitBreaker.Metrics.class); // when when(registry.getAllCircuitBreakers()).thenReturn(Array.ofAll(expectedStateToCircuitBreaker.values())); boolean allowHealthIndicatorToFail = true; expectedStateToCircuitBreaker.forEach( (state, circuitBreaker) -> setCircuitBreakerWhen(state, circuitBreaker, config, metrics, instanceProperties, circuitBreakerProperties, allowHealthIndicatorToFail)); CircuitBreakersHealthIndicator healthIndicator = new CircuitBreakersHealthIndicator(registry, circuitBreakerProperties, new SimpleStatusAggregator()); // then Health health = healthIndicator.health(); then(health.getStatus()).isEqualTo(Status.DOWN); then(health.getDetails()).containsKeys(OPEN.name(), HALF_OPEN.name(), CLOSED.name()); assertState(OPEN, Status.DOWN, health.getDetails()); assertState(HALF_OPEN, new Status("CIRCUIT_HALF_OPEN"), health.getDetails()); assertState(CLOSED, Status.UP, health.getDetails()); }
Example 18
Source File: RetrofitCircuitBreakerTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void decorateCancelledEnqueuedCall() throws Exception { stubFor(get(urlPathEqualTo("/greeting")) .willReturn(aResponse() .withFixedDelay(500) .withStatus(200) .withHeader("Content-Type", "text/plain") .withBody("hello world"))); Call<String> call = service.greeting(); cancelAsync(call, 100); EnqueueDecorator.performCatchingEnqueue(call); final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfFailedCalls()) .describedAs("Failed calls") .isEqualTo(0); // Circuit breaker should still be closed, not hit open threshold assertThat(circuitBreaker.getState()) .isEqualTo(CircuitBreaker.State.CLOSED); EnqueueDecorator.performCatchingEnqueue(service.greeting()); EnqueueDecorator.performCatchingEnqueue(service.greeting()); EnqueueDecorator.performCatchingEnqueue(service.greeting()); assertThat(metrics.getNumberOfFailedCalls()) .isEqualTo(3); // Circuit breaker should be OPEN, threshold met assertThat(circuitBreaker.getState()) .isEqualTo(CircuitBreaker.State.OPEN); }
Example 19
Source File: CircularEventConsumerTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldBufferAllEvents() { CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() .slidingWindowSize(3) .ignoreExceptions(IOException.class) .build(); CircuitBreaker circuitBreaker = CircuitBreaker.of("testName", circuitBreakerConfig); CircularEventConsumer<CircuitBreakerEvent> ringBuffer = new CircularEventConsumer<>(10); circuitBreaker.getEventPublisher().onEvent(ringBuffer); assertThat(ringBuffer.getBufferedEvents()).isEmpty(); circuitBreaker.onSuccess(0, TimeUnit.NANOSECONDS); circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla")); circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new IOException("Bla")); circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla")); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(3); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(2); circuitBreaker.reset(); CircuitBreaker.Metrics resetMetrics = circuitBreaker.getMetrics(); assertThat(resetMetrics.getNumberOfBufferedCalls()).isEqualTo(0); assertThat(resetMetrics.getNumberOfFailedCalls()).isEqualTo(0); //Because circuit emits 2 error events and one state transition event assertThat(ringBuffer.getBufferedEvents()).hasSize(8); assertThat(ringBuffer.getBufferedEvents()).extracting("eventType") .containsExactly(Type.SUCCESS, Type.ERROR, Type.IGNORED_ERROR, Type.ERROR, Type.FAILURE_RATE_EXCEEDED, Type.STATE_TRANSITION, Type.STATE_TRANSITION, Type.RESET); }
Example 20
Source File: CircuitBreakersHealthIndicatorTest.java From resilience4j with Apache License 2.0 | 4 votes |
@Test public void healthMetricsAndConfig() { // given CircuitBreakerConfig config = mock(CircuitBreakerConfig.class); CircuitBreakerRegistry registry = mock(CircuitBreakerRegistry.class); CircuitBreaker.Metrics metrics = mock(CircuitBreaker.Metrics.class); CircuitBreaker circuitBreaker = mock(CircuitBreaker.class); CircuitBreakerConfigurationProperties.InstanceProperties instanceProperties = mock(CircuitBreakerConfigurationProperties.InstanceProperties.class); CircuitBreakerConfigurationProperties circuitBreakerProperties = mock( CircuitBreakerConfigurationProperties.class); CircuitBreakersHealthIndicator healthIndicator = new CircuitBreakersHealthIndicator(registry, circuitBreakerProperties, new SimpleStatusAggregator()); //when when(config.getFailureRateThreshold()).thenReturn(30f); when(metrics.getFailureRate()).thenReturn(20f); when(metrics.getSlowCallRate()).thenReturn(20f); when(config.getSlowCallRateThreshold()).thenReturn(50f); when(metrics.getNumberOfBufferedCalls()).thenReturn(100); when(metrics.getNumberOfFailedCalls()).thenReturn(20); when(metrics.getNumberOfSlowCalls()).thenReturn(20); when(metrics.getNumberOfNotPermittedCalls()).thenReturn(0L); when(registry.getAllCircuitBreakers()).thenReturn(Array.of(circuitBreaker)); when(circuitBreaker.getName()).thenReturn("test"); when(circuitBreakerProperties.findCircuitBreakerProperties("test")) .thenReturn(Optional.of(instanceProperties)); when(instanceProperties.getRegisterHealthIndicator()).thenReturn(true); when(instanceProperties.getAllowHealthIndicatorToFail()).thenReturn(true); when(circuitBreaker.getMetrics()).thenReturn(metrics); when(circuitBreaker.getCircuitBreakerConfig()).thenReturn(config); when(circuitBreaker.getState()).thenReturn(CLOSED, OPEN, HALF_OPEN, CLOSED); // then Health health = healthIndicator.health(); then(health.getStatus()).isEqualTo(Status.UP); then(health.getDetails()).containsKey("test"); then(health.getDetails().get("test")).isInstanceOf(Health.class); then(((Health) health.getDetails().get("test")).getDetails()) .contains( entry("failureRate", "20.0%"), entry("slowCallRate", "20.0%"), entry("slowCallRateThreshold", "50.0%"), entry("failureRateThreshold", "30.0%"), entry("bufferedCalls", 100), entry("slowCalls", 20), entry("failedCalls", 20), entry("notPermittedCalls", 0L) ); }