io.github.resilience4j.timelimiter.TimeLimiter Java Examples
The following examples show how to use
io.github.resilience4j.timelimiter.TimeLimiter.
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: ResilienceHandler.java From cloud-espm-cloud-native with Apache License 2.0 | 7 votes |
/** * This method returns a desired Tax(taxAmount, taxPercentage) value when the TaxService is up. * If the TaxService is down, it applies a combination of following fault tolerance patterns * in a sequence: TimeLimiter, CircuitBreaker and Retry using a Callable. When all the attempts * are exhausted it calls a fallback method to recover from failure and offers the default tax value. * * @param amount * @return */ public Tax applyResiliencePatterns(BigDecimal amount) { CircuitBreaker circuitBreaker = configureCircuitBreaker(); TimeLimiter timeLimiter = configureTimeLimiter(); Retry retry = configureRetry(); Supplier<CompletableFuture<Tax>> futureSupplier = () -> CompletableFuture.supplyAsync(() -> salesOrderService.supplyTax(amount)); Callable<Tax> callable = TimeLimiter.decorateFutureSupplier(timeLimiter, futureSupplier); callable = CircuitBreaker.decorateCallable(circuitBreaker, callable); callable = Retry.decorateCallable(retry, callable); //Executing the decorated callable and recovering from any exception by calling the fallback method Try<Tax> result = Try.ofCallable(callable).recover(throwable -> taxServiceFallback(amount)); return result.get(); }
Example #2
Source File: AbstractTimeLimiterMetricsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldRegisterMetrics() throws Exception { TimeLimiter timeLimiter = given(metricRegistry); String expectedPrefix = "resilience4j.timelimiter.testLimit."; Supplier<CompletableFuture<String>> futureSupplier = () -> CompletableFuture.completedFuture("Hello world"); String result = timeLimiter.decorateFutureSupplier(futureSupplier).call(); then(result).isEqualTo("Hello world"); assertThat(metricRegistry).hasMetricsSize(3); assertThat(metricRegistry).counter(expectedPrefix + SUCCESSFUL) .hasValue(1L); assertThat(metricRegistry).counter(expectedPrefix + FAILED) .hasValue(0L); assertThat(metricRegistry).counter(expectedPrefix + TIMEOUT) .hasValue(0L); }
Example #3
Source File: TimeLimiterMetricsPublisher.java From resilience4j with Apache License 2.0 | 6 votes |
@Override public void publishMetrics(TimeLimiter timeLimiter) { String name = timeLimiter.getName(); String successfulName = name(prefix, name, SUCCESSFUL); String failedName = name(prefix, name, FAILED); String timeoutName = name(prefix, name, TIMEOUT); Counter successes = metricRegistry.counter(successfulName); Counter failures = metricRegistry.counter(failedName); Counter timeouts = metricRegistry.counter(timeoutName); timeLimiter.getEventPublisher().onSuccess(event -> successes.inc()); timeLimiter.getEventPublisher().onError(event -> failures.inc()); timeLimiter.getEventPublisher().onTimeout(event -> timeouts.inc()); List<String> metricNames = Arrays.asList(successfulName, failedName, timeoutName); metricsNameMap.put(name, new HashSet<>(metricNames)); }
Example #4
Source File: Resilience4jTest.java From spring-cloud-formula with Apache License 2.0 | 6 votes |
@Test public void testTimeout() throws Throwable { Callable<Object> callable = () -> { Thread.sleep(10000); return null; }; Supplier<Future<Object>> supplier = () -> executorService.submit(callable); // Wrap your call to BackendService.doSomething() in a future provided by your executor Callable<Object> result = TimeLimiter.decorateFutureSupplier(timeLimiter, supplier); long start = System.currentTimeMillis(); try { result.call(); fail("fail"); } catch (Throwable t) { long cost = System.currentTimeMillis() - start; assertThat(cost, Matchers.lessThan(1010L)); assertThat(t, Matchers.instanceOf(TimeoutException.class)); } }
Example #5
Source File: Resilience4jTest.java From spring-cloud-formula with Apache License 2.0 | 6 votes |
@Before public void init() { TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() .timeoutDuration(Duration.ofSeconds(1)) .cancelRunningFuture(true) .build(); timeLimiter = TimeLimiter.of(timeLimiterConfig); CustomizableThreadFactory factory = new CustomizableThreadFactory("timeLimiter-"); factory.setDaemon(true); executorService = Executors.newCachedThreadPool(factory); CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig .custom() .enableAutomaticTransitionFromOpenToHalfOpen() .failureRateThreshold(50) .ringBufferSizeInClosedState(10) .ringBufferSizeInHalfOpenState(2) .build(); circuitBreaker = CircuitBreaker.of("backendName", circuitBreakerConfig); }
Example #6
Source File: TimeLimiterMetricsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldRecordTimeouts() { TimeLimiter timeLimiter = TimeLimiter.of(TimeLimiterConfig.custom() .timeoutDuration(Duration.ZERO) .build()); metricRegistry.registerAll(TimeLimiterMetrics.ofTimeLimiter(timeLimiter)); timeLimiter.onError(new TimeoutException()); timeLimiter.onError(new TimeoutException()); assertThat(metricRegistry).hasMetricsSize(3); assertThat(metricRegistry).counter(DEFAULT_PREFIX + SUCCESSFUL) .hasValue(0L); assertThat(metricRegistry).counter(DEFAULT_PREFIX + FAILED) .hasValue(0L); assertThat(metricRegistry).counter(DEFAULT_PREFIX + TIMEOUT) .hasValue(2L); }
Example #7
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 #8
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 #9
Source File: TimeLimiterMetrics.java From resilience4j with Apache License 2.0 | 6 votes |
private TimeLimiterMetrics(String prefix, Iterable<TimeLimiter> timeLimiters, MetricRegistry metricRegistry) { requireNonNull(prefix, PREFIX_NULL); requireNonNull(timeLimiters, ITERABLE_NULL); requireNonNull(metricRegistry); this.metricRegistry = metricRegistry; timeLimiters.forEach(timeLimiter -> { String name = timeLimiter.getName(); Counter successes = metricRegistry.counter(name(prefix, name, SUCCESSFUL)); Counter failures = metricRegistry.counter(name(prefix, name, FAILED)); Counter timeouts = metricRegistry.counter(name(prefix, name, TIMEOUT)); timeLimiter.getEventPublisher().onSuccess(event -> successes.inc()); timeLimiter.getEventPublisher().onError(event -> failures.inc()); timeLimiter.getEventPublisher().onTimeout(event -> timeouts.inc()); } ); }
Example #10
Source File: TimeLimiterTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldThrowTimeoutExceptionWithCompletionStage() throws Exception { Duration timeoutDuration = Duration.ofMillis(300); TimeLimiter timeLimiter = TimeLimiter.of(timeoutDuration); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); Supplier<CompletionStage<Integer>> supplier = () -> CompletableFuture.supplyAsync(() -> { try { // sleep for timeout. Thread.sleep(500); } catch (InterruptedException e) { // nothing } return 0; }); CompletionStage<Integer> decorated = TimeLimiter .decorateCompletionStage(timeLimiter, scheduler, supplier).get(); Try<Integer> decoratedResult = Try.ofCallable(() -> decorated.toCompletableFuture().get()); assertThat(decoratedResult.isFailure()).isTrue(); assertThat(decoratedResult.getCause()).isInstanceOf(ExecutionException.class) .hasCauseExactlyInstanceOf(TimeoutException.class); }
Example #11
Source File: TimeLimiterTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldThrowTimeoutExceptionAndNotInvokeCancel() throws Exception { Duration timeoutDuration = Duration.ofSeconds(1); TimeLimiter timeLimiter = TimeLimiter .of(TimeLimiterConfig.custom().timeoutDuration(timeoutDuration) .cancelRunningFuture(false).build()); @SuppressWarnings("unchecked") Future<Integer> mockFuture = (Future<Integer>) mock(Future.class); Supplier<Future<Integer>> supplier = () -> mockFuture; given(mockFuture.get(timeoutDuration.toMillis(), TimeUnit.MILLISECONDS)) .willThrow(new TimeoutException()); Callable<Integer> decorated = TimeLimiter.decorateFutureSupplier(timeLimiter, supplier); Try<Integer> decoratedResult = Try.ofCallable(decorated); assertThat(decoratedResult.isFailure()).isTrue(); assertThat(decoratedResult.getCause()).isInstanceOf(TimeoutException.class); then(mockFuture).should(never()).cancel(true); }
Example #12
Source File: TimeLimiterTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldReturnResult() throws Exception { Duration timeoutDuration = Duration.ofSeconds(1); TimeLimiter timeLimiter = TimeLimiter.of(timeoutDuration); @SuppressWarnings("unchecked") Future<Integer> mockFuture = (Future<Integer>) mock(Future.class); Supplier<Future<Integer>> supplier = () -> mockFuture; given(mockFuture.get(timeoutDuration.toMillis(), TimeUnit.MILLISECONDS)).willReturn(42); int result = timeLimiter.executeFutureSupplier(supplier); assertThat(result).isEqualTo(42); int result2 = timeLimiter.decorateFutureSupplier(supplier).call(); assertThat(result2).isEqualTo(42); }
Example #13
Source File: TimeLimiterMetricsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldRecordErrors() { TimeLimiter timeLimiter = TimeLimiter.of(TimeLimiterConfig.ofDefaults()); metricRegistry.registerAll(TimeLimiterMetrics.ofTimeLimiter(timeLimiter)); timeLimiter.onError(new RuntimeException()); timeLimiter.onError(new RuntimeException()); assertThat(metricRegistry).hasMetricsSize(3); assertThat(metricRegistry).counter(DEFAULT_PREFIX + SUCCESSFUL) .hasValue(0L); assertThat(metricRegistry).counter(DEFAULT_PREFIX + FAILED) .hasValue(2L); assertThat(metricRegistry).counter(DEFAULT_PREFIX + TIMEOUT) .hasValue(0L); }
Example #14
Source File: TimeLimiterTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldReturnResultWithCompletionStage() throws Exception { Duration timeoutDuration = Duration.ofSeconds(1); TimeLimiter timeLimiter = TimeLimiter.of(timeoutDuration); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); Supplier<CompletionStage<Integer>> supplier = () -> CompletableFuture.supplyAsync(() -> { try { // sleep but not timeout. Thread.sleep(500); } catch (InterruptedException e) { // nothing } return 42; }); int result = timeLimiter.executeCompletionStage(scheduler, supplier).toCompletableFuture() .get(); assertThat(result).isEqualTo(42); int result2 = timeLimiter.decorateCompletionStage(scheduler, supplier).get() .toCompletableFuture().get(); assertThat(result2).isEqualTo(42); }
Example #15
Source File: InMemoryTimeLimiterRegistryTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("unchecked") public void timeLimiterPositiveWithSupplier() { TimeLimiterRegistry registry = new InMemoryTimeLimiterRegistry(config); Supplier<TimeLimiterConfig> timeLimiterConfigSupplier = mock(Supplier.class); given(timeLimiterConfigSupplier.get()).willReturn(config); TimeLimiter firstTimeLimiter = registry.timeLimiter("test", timeLimiterConfigSupplier); verify(timeLimiterConfigSupplier, times(1)).get(); TimeLimiter sameAsFirst = registry.timeLimiter("test", timeLimiterConfigSupplier); verify(timeLimiterConfigSupplier, times(1)).get(); TimeLimiter anotherLimit = registry.timeLimiter("test1", timeLimiterConfigSupplier); verify(timeLimiterConfigSupplier, times(2)).get(); then(firstTimeLimiter).isEqualTo(sameAsFirst); then(firstTimeLimiter).isNotEqualTo(anotherLimit); }
Example #16
Source File: CircuitBreakerManager.java From spring-cloud-formula with Apache License 2.0 | 6 votes |
private TimeLimiterCoalition createTimeLimiter(String ruleName, CircuitBreakerRule rule) { if (rule == null) { return null; } Duration timeout = rule.getTimeoutDuration(); if (rule.getEnabled() != null && rule.getEnabled() && timeout != null && !timeout.isNegative() && !timeout.isZero()) { try { TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() .timeoutDuration(rule.getTimeoutDuration()) .cancelRunningFuture(rule.getCancelRunningFuture()) .build(); TimeLimiter timeLimiter = TimeLimiter.of(timeLimiterConfig); TimeLimiterCoalition timeLimiterCoalition = new TimeLimiterCoalition( timeLimiter, rule); return timeLimiterCoalition; } catch (Exception e) { logger.error("failed to create timeLimiter,name:{},id{}", ruleName, rule.getRuleId(), e); return null; } } return null; }
Example #17
Source File: RxJava2TimeLimiterAspectExt.java From resilience4j with Apache License 2.0 | 5 votes |
/** * @param proceedingJoinPoint Spring AOP proceedingJoinPoint * @param timeLimiter the configured timeLimiter * @param methodName the method name * @return the result object * @throws Throwable exception in case of faulty flow */ @Override public Object handle(ProceedingJoinPoint proceedingJoinPoint, TimeLimiter timeLimiter, String methodName) throws Throwable { TimeLimiterTransformer<?> timeLimiterTransformer = TimeLimiterTransformer.of(timeLimiter); Object returnValue = proceedingJoinPoint.proceed(); return executeRxJava2Aspect(timeLimiterTransformer, returnValue, methodName); }
Example #18
Source File: Resilience4jUnitTest.java From tutorials with MIT License | 5 votes |
@SuppressWarnings("unchecked") @Test public void whenTimeLimiterIsUsed_thenItWorksAsExpected() throws Exception { long ttl = 1; TimeLimiterConfig config = TimeLimiterConfig.custom().timeoutDuration(Duration.ofMillis(ttl)).build(); TimeLimiter timeLimiter = TimeLimiter.of(config); Future futureMock = mock(Future.class); Callable restrictedCall = TimeLimiter.decorateFutureSupplier(timeLimiter, () -> futureMock); restrictedCall.call(); verify(futureMock).get(ttl, TimeUnit.MILLISECONDS); }
Example #19
Source File: AbstractTimeLimiterConfigurationOnMissingBean.java From resilience4j with Apache License 2.0 | 5 votes |
@Bean @ConditionalOnMissingBean public TimeLimiterRegistry timeLimiterRegistry( TimeLimiterConfigurationProperties timeLimiterProperties, EventConsumerRegistry<TimeLimiterEvent> timeLimiterEventsConsumerRegistry, RegistryEventConsumer<TimeLimiter> timeLimiterRegistryEventConsumer, @Qualifier("compositeTimeLimiterCustomizer") CompositeCustomizer<TimeLimiterConfigCustomizer> compositeTimeLimiterCustomizer) { return timeLimiterConfiguration.timeLimiterRegistry( timeLimiterProperties, timeLimiterEventsConsumerRegistry, timeLimiterRegistryEventConsumer, compositeTimeLimiterCustomizer); }
Example #20
Source File: TaggedTimeLimiterMetricsPublisherTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void testReplaceNewMeter(){ TimeLimiter oldOne = TimeLimiter.of("backendC", TimeLimiterConfig.ofDefaults()); // add meters of old taggedTimeLimiterMetricsPublisher.addMetrics(meterRegistry, oldOne); // one success call oldOne.onSuccess(); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap).containsKeys("backendC"); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap.get("backendC")).hasSize(3); Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters(); Optional<Counter> successful = findMeterByKindAndNameTags(counters, "successful", oldOne.getName()); assertThat(successful).map(Counter::count).contains(1d); TimeLimiter newOne = TimeLimiter.of("backendC", TimeLimiterConfig.ofDefaults()); // add meters of new taggedTimeLimiterMetricsPublisher.addMetrics(meterRegistry, newOne); // three success call newOne.onSuccess(); newOne.onSuccess(); newOne.onSuccess(); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap).containsKeys("backendC"); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap.get("backendC")).hasSize(3); counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters(); successful = findMeterByKindAndNameTags(counters, "successful", newOne.getName()); assertThat(successful).map(Counter::count).contains(3d); }
Example #21
Source File: TimeLimiterConfigurationTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void testTimeLimiterRegistry() { // Given io.github.resilience4j.common.timelimiter.configuration.TimeLimiterConfigurationProperties.InstanceProperties instanceProperties1 = new io.github.resilience4j.common.timelimiter.configuration.TimeLimiterConfigurationProperties.InstanceProperties(); instanceProperties1.setTimeoutDuration(Duration.ofSeconds(3)); io.github.resilience4j.common.timelimiter.configuration.TimeLimiterConfigurationProperties.InstanceProperties instanceProperties2 = new io.github.resilience4j.common.timelimiter.configuration.TimeLimiterConfigurationProperties.InstanceProperties(); instanceProperties2.setTimeoutDuration(Duration.ofSeconds(2)); TimeLimiterConfigurationProperties timeLimiterConfigurationProperties = new TimeLimiterConfigurationProperties(); timeLimiterConfigurationProperties.getInstances().put("backend1", instanceProperties1); timeLimiterConfigurationProperties.getInstances().put("backend2", instanceProperties2); timeLimiterConfigurationProperties.setTimeLimiterAspectOrder(200); TimeLimiterConfiguration timeLimiterConfiguration = new TimeLimiterConfiguration(); DefaultEventConsumerRegistry<TimeLimiterEvent> eventConsumerRegistry = new DefaultEventConsumerRegistry<>(); // When TimeLimiterRegistry timeLimiterRegistry = timeLimiterConfiguration.timeLimiterRegistry(timeLimiterConfigurationProperties, eventConsumerRegistry, new CompositeRegistryEventConsumer<>(emptyList()), compositeTimeLimiterCustomizerTestInstance()); // Then assertThat(timeLimiterConfigurationProperties.getTimeLimiterAspectOrder()).isEqualTo(200); assertThat(timeLimiterRegistry.getAllTimeLimiters().size()).isEqualTo(2); TimeLimiter timeLimiter1 = timeLimiterRegistry.timeLimiter("backend1"); assertThat(timeLimiter1).isNotNull(); assertThat(timeLimiter1.getTimeLimiterConfig().getTimeoutDuration()).isEqualTo(Duration.ofSeconds(3)); TimeLimiter timeLimiter2 = timeLimiterRegistry.timeLimiter("backend2"); assertThat(timeLimiter2).isNotNull(); assertThat(timeLimiter2.getTimeLimiterConfig().getTimeoutDuration()).isEqualTo(Duration.ofSeconds(2)); assertThat(eventConsumerRegistry.getAllEventConsumer()).hasSize(2); }
Example #22
Source File: AbstractTimeLimiterMetrics.java From resilience4j with Apache License 2.0 | 5 votes |
protected void registerMetrics(MeterRegistry meterRegistry, TimeLimiter timeLimiter, List<Tag> customTags) { // Remove previous meters before register removeMetrics(meterRegistry, timeLimiter.getName()); Counter successes = Counter.builder(names.getCallsMetricName()) .description("The number of successful calls") .tag(TagNames.NAME, timeLimiter.getName()) .tag(TagNames.KIND, KIND_SUCCESSFUL) .tags(customTags) .register(meterRegistry); Counter failures = Counter.builder(names.getCallsMetricName()) .description("The number of failed calls") .tag(TagNames.NAME, timeLimiter.getName()) .tag(TagNames.KIND, KIND_FAILED) .tags(customTags) .register(meterRegistry); Counter timeouts = Counter.builder(names.getCallsMetricName()) .description("The number of timed out calls") .tag(TagNames.NAME, timeLimiter.getName()) .tag(TagNames.KIND, KIND_TIMEOUT) .tags(customTags) .register(meterRegistry); timeLimiter.getEventPublisher() .onSuccess(event -> successes.increment()) .onError(event -> failures.increment()) .onTimeout(event -> timeouts.increment()); List<Meter.Id> ids = Arrays.asList(successes.getId(), failures.getId(), timeouts.getId()); meterIdMap.put(timeLimiter.getName(), new HashSet<>(ids)); }
Example #23
Source File: TaggedTimeLimiterMetrics.java From resilience4j with Apache License 2.0 | 5 votes |
@Override public void bindTo(MeterRegistry registry) { for (TimeLimiter timeLimiter : timeLimiterRegistry.getAllTimeLimiters()) { addMetrics(registry, timeLimiter); } timeLimiterRegistry.getEventPublisher() .onEntryAdded(event -> addMetrics(registry, event.getAddedEntry())); timeLimiterRegistry.getEventPublisher() .onEntryRemoved(event -> removeMetrics(registry, event.getRemovedEntry().getName())); timeLimiterRegistry.getEventPublisher().onEntryReplaced(event -> { removeMetrics(registry, event.getOldEntry().getName()); addMetrics(registry, event.getNewEntry()); }); }
Example #24
Source File: TimeLimiterMetricsPublisherTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void customMetricNamesOverrideDefaultOnes() { TimeLimiterMetricsPublisher.MetricNames names = TimeLimiterMetricsPublisher.MetricNames .custom() .callsMetricName("custom_calls") .build(); CollectorRegistry customRegistry = new CollectorRegistry(); TimeLimiterMetricsPublisher timeLimiterMetricsPublisher = new TimeLimiterMetricsPublisher( names); timeLimiterMetricsPublisher.register(customRegistry); TimeLimiterRegistry timeLimiterRegistry = TimeLimiterRegistry .of(TimeLimiterConfig.ofDefaults(), timeLimiterMetricsPublisher); TimeLimiter timeLimiter = timeLimiterRegistry.timeLimiter("backendA"); timeLimiter.onSuccess(); timeLimiter.onError(new RuntimeException()); timeLimiter.onError(new TimeoutException()); Double successfulCalls = getSampleValue(customRegistry, "custom_calls", KIND_SUCCESSFUL); Double failedCalls = getSampleValue(customRegistry, "custom_calls", KIND_FAILED); Double timeoutCalls = getSampleValue(customRegistry, "custom_calls", KIND_TIMEOUT); assertThat(successfulCalls).isNotNull(); assertThat(failedCalls).isNotNull(); assertThat(timeoutCalls).isNotNull(); }
Example #25
Source File: TimeLimiterMetricsTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Override protected TimeLimiter given(String prefix, MetricRegistry metricRegistry) { TimeLimiterRegistry timeLimiterRegistry = TimeLimiterRegistry.ofDefaults(); TimeLimiter timeLimiter = timeLimiterRegistry.timeLimiter("testLimit"); metricRegistry .registerAll(TimeLimiterMetrics.ofTimeLimiterRegistry(prefix, timeLimiterRegistry)); return timeLimiter; }
Example #26
Source File: TimeLimiterMetricsPublisher.java From resilience4j with Apache License 2.0 | 5 votes |
@Override public void publishMetrics(TimeLimiter entry) { String name = entry.getName(); entry.getEventPublisher() .onSuccess(event -> callsCounter.labels(name, KIND_SUCCESSFUL).inc()) .onError(event -> callsCounter.labels(name, KIND_FAILED).inc()) .onTimeout(event -> callsCounter.labels(name, KIND_TIMEOUT).inc()); }
Example #27
Source File: RxJava2TimeLimiterAspectExtTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldThrowIllegalArgumentExceptionWithNotRxJava2Type() throws Throwable{ TimeLimiter timeLimiter = TimeLimiter.ofDefaults("test"); when(proceedingJoinPoint.proceed()).thenReturn("NOT RXJAVA2 TYPE"); try { rxJava2TimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod"); fail("exception missed"); } catch (Throwable e) { assertThat(e).isInstanceOf(IllegalReturnTypeException.class) .hasMessage( "java.lang.String testMethod has unsupported by @TimeLimiter return type. RxJava2 expects Flowable/Single/..."); } }
Example #28
Source File: ReactorTimeLimiterAspectExtTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void testReactorTypes() throws Throwable { TimeLimiter timeLimiter = TimeLimiter.ofDefaults("test"); when(proceedingJoinPoint.proceed()).thenReturn(Mono.just("Test")); assertThat(reactorTimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod")).isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Flux.just("Test")); assertThat(reactorTimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod")).isNotNull(); }
Example #29
Source File: ReactorTimeLimiterAspectExtTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldThrowIllegalArgumentExceptionWithNotReactorType() throws Throwable{ TimeLimiter timeLimiter = TimeLimiter.ofDefaults("test"); when(proceedingJoinPoint.proceed()).thenReturn("NOT REACTOR TYPE"); try { reactorTimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod"); fail("exception missed"); } catch (Throwable e) { assertThat(e).isInstanceOf(IllegalReturnTypeException.class) .hasMessage( "java.lang.String testMethod has unsupported by @TimeLimiter return type. Reactor expects Mono/Flux."); } }
Example #30
Source File: RxJava2TimeLimiterAspectExtTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void testRxJava2Types() throws Throwable { TimeLimiter timeLimiter = TimeLimiter.ofDefaults("test"); when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test")); assertThat(rxJava2TimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod")).isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Flowable.just("Test")); assertThat(rxJava2TimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod")).isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Observable.just("Test")); assertThat(rxJava2TimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod")).isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Completable.complete()); assertThat(rxJava2TimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod")).isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Maybe.just("Test")); assertThat(rxJava2TimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod")).isNotNull(); }