Java Code Examples for io.github.resilience4j.timelimiter.TimeLimiter#of()

The following examples show how to use io.github.resilience4j.timelimiter.TimeLimiter#of() . 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: Resilience4jTest.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: TimeLimiterMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: TimeLimiterMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: TimeLimiterMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRecordSuccesses() {
    TimeLimiter timeLimiter = TimeLimiter.of(TimeLimiterConfig.ofDefaults());
    metricRegistry.registerAll(TimeLimiterMetrics.ofTimeLimiter(timeLimiter));

    timeLimiter.onSuccess();
    timeLimiter.onSuccess();

    assertThat(metricRegistry).hasMetricsSize(3);
    assertThat(metricRegistry).counter(DEFAULT_PREFIX + SUCCESSFUL)
        .hasValue(2L);
    assertThat(metricRegistry).counter(DEFAULT_PREFIX + FAILED)
        .hasValue(0L);
    assertThat(metricRegistry).counter(DEFAULT_PREFIX + TIMEOUT)
        .hasValue(0L);
}
 
Example 5
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 6
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 7
Source File: TimeLimiterTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@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 8
Source File: TimeLimiterTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@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 9
Source File: TimeLimiterTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@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 10
Source File: TimeLimiterTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@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 vote down vote up
@Test
public void shouldThrowTimeoutExceptionAndInvokeCancel() throws Exception {
    Duration timeoutDuration = Duration.ofSeconds(1);
    TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
        .timeoutDuration(timeoutDuration)
        .build();
    TimeLimiter timeLimiter = TimeLimiter.of(TIME_LIMITER_NAME,timeLimiterConfig);

    @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);
    assertThat(decoratedResult.getCause()).hasMessage(createdTimeoutExceptionWithName(TIME_LIMITER_NAME).getMessage());

    then(mockFuture).should().cancel(true);
}
 
Example 12
Source File: CircuitBreakerManager.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
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 13
Source File: TaggedTimeLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@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 14
Source File: TimeLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnCorrectTimeoutDuration() {
    Duration timeoutDuration = Duration.ofSeconds(1);
    TimeLimiter timeLimiter = TimeLimiter.of(timeoutDuration);
    assertThat(timeLimiter).isNotNull();
    assertThat(timeLimiter.getTimeLimiterConfig().getTimeoutDuration())
        .isEqualTo(timeoutDuration);
}
 
Example 15
Source File: ResilienceHandler.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
/**
 * Creating a TimeLimiter using custom configuration
 * 
 * @return
 */
private TimeLimiter configureTimeLimiter() {
	TimeLimiterConfig timeLimiterConfig = 
			TimeLimiterConfig.custom()
							.timeoutDuration(Duration.ofMillis(1000))
							.cancelRunningFuture(false).build();
	TimeLimiter timeLimiter = TimeLimiter.of(timeLimiterConfig);
	return timeLimiter;
}
 
Example 16
Source File: Resilience4jUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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 17
Source File: Resilience4JCircuitBreaker.java    From spring-cloud-circuitbreaker with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
	TimeLimiter timeLimiter = TimeLimiter.of(timeLimiterConfig);
	Supplier<Future<T>> futureSupplier = () -> executorService.submit(toRun::get);
	Callable restrictedCall = TimeLimiter.decorateFutureSupplier(timeLimiter,
			futureSupplier);

	io.github.resilience4j.circuitbreaker.CircuitBreaker defaultCircuitBreaker = registry
			.circuitBreaker(id, circuitBreakerConfig);
	circuitBreakerCustomizer
			.ifPresent(customizer -> customizer.customize(defaultCircuitBreaker));
	Callable<T> callable = io.github.resilience4j.circuitbreaker.CircuitBreaker
			.decorateCallable(defaultCircuitBreaker, restrictedCall);
	return Try.of(callable::call).recover(fallback).get();
}