io.github.resilience4j.ratelimiter.RateLimiter Java Examples

The following examples show how to use io.github.resilience4j.ratelimiter.RateLimiter. 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: AbstractRateLimiterMetricsTest.java    From resilience4j with Apache License 2.0 7 votes vote down vote up
@Test
public void shouldRegisterMetrics() throws Throwable {
    RateLimiter rateLimiter = givenMetricRegistry(metricRegistry);
    given(helloWorldService.returnHelloWorld()).willReturn("Hello world");

    String value = rateLimiter.executeSupplier(helloWorldService::returnHelloWorld);

    assertThat(value).isEqualTo("Hello world");
    then(helloWorldService).should(times(1)).returnHelloWorld();
    assertThat(metricRegistry.getMetrics()).hasSize(2);
    assertThat(metricRegistry.getGauges()
        .get("resilience4j.ratelimiter.testLimit.number_of_waiting_threads")
        .getValue()).isEqualTo(0);
    assertThat(metricRegistry.getGauges()
        .get("resilience4j.ratelimiter.testLimit.available_permissions").getValue())
        .isIn(DEFAULT_LIMIT_FOR_PERIOD, DEFAULT_LIMIT_FOR_PERIOD - 1);
}
 
Example #2
Source File: TaggedRateLimiterMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Gauge availablePermissions = meterRegistry.get(DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME)
        .gauge();

    assertThat(availablePermissions).isNotNull();
    assertThat(availablePermissions.value())
        .isEqualTo(rateLimiter.getMetrics().getAvailablePermissions());
    assertThat(availablePermissions.getId().getTag(TagNames.NAME))
        .isEqualTo(rateLimiter.getName());

    RateLimiter newRateLimiter = RateLimiter
        .of(rateLimiter.getName(), RateLimiterConfig.custom().limitForPeriod(1000).build());

    rateLimiterRegistry.replace(rateLimiter.getName(), newRateLimiter);

    availablePermissions = meterRegistry.get(DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME).gauge();

    assertThat(availablePermissions).isNotNull();
    assertThat(availablePermissions.value())
        .isEqualTo(newRateLimiter.getMetrics().getAvailablePermissions());
    assertThat(availablePermissions.getId().getTag(TagNames.NAME))
        .isEqualTo(newRateLimiter.getName());
}
 
Example #3
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 #4
Source File: InMemoryRateLimiterRegistryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void rateLimiterPositiveWithSupplier() throws Exception {
    RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
    Supplier<RateLimiterConfig> rateLimiterConfigSupplier = mock(Supplier.class);
    when(rateLimiterConfigSupplier.get())
        .thenReturn(config);

    RateLimiter firstRateLimiter = registry.rateLimiter("test", rateLimiterConfigSupplier);
    verify(rateLimiterConfigSupplier, times(1)).get();
    RateLimiter sameAsFirst = registry.rateLimiter("test", rateLimiterConfigSupplier);
    verify(rateLimiterConfigSupplier, times(1)).get();
    RateLimiter anotherLimit = registry.rateLimiter("test1", rateLimiterConfigSupplier);
    verify(rateLimiterConfigSupplier, times(2)).get();

    then(firstRateLimiter).isEqualTo(sameAsFirst);
    then(firstRateLimiter).isNotEqualTo(anotherLimit);
}
 
Example #5
Source File: ReactorRateLimiterAspectExt.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * handle the Spring web flux (Flux /Mono) return types AOP based into reactor rate limiter See
 * {@link RateLimiter} for details.
 *
 * @param proceedingJoinPoint Spring AOP proceedingJoinPoint
 * @param rateLimiter         the configured rateLimiter
 * @param methodName          the method name
 * @return the result object
 * @throws Throwable exception in case of faulty flow
 */
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter,
    String methodName) throws Throwable {
    Object returnValue = proceedingJoinPoint.proceed();
    if (Flux.class.isAssignableFrom(returnValue.getClass())) {
        Flux<?> fluxReturnValue = (Flux<?>) returnValue;
        return fluxReturnValue.transformDeferred(RateLimiterOperator.of(rateLimiter));
    } else if (Mono.class.isAssignableFrom(returnValue.getClass())) {
        Mono<?> monoReturnValue = (Mono<?>) returnValue;
        return monoReturnValue.transformDeferred(RateLimiterOperator.of(rateLimiter));
    } else {
        logger.error("Unsupported type for Reactor rateLimiter {}",
            returnValue.getClass().getTypeName());
        throw new IllegalArgumentException(
            "Not Supported type for the rateLimiter in Reactor :" + returnValue.getClass()
                .getName());

    }
}
 
Example #6
Source File: TaggedRateLimiterMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddMetricsForANewlyCreatedRateLimiter() {
    RateLimiter newRateLimiter = rateLimiterRegistry.rateLimiter("backendB");

    assertThat(taggedRateLimiterMetrics.meterIdMap).containsKeys("backendA", "backendB");
    assertThat(taggedRateLimiterMetrics.meterIdMap.get("backendA")).hasSize(2);
    assertThat(taggedRateLimiterMetrics.meterIdMap.get("backendB")).hasSize(2);

    List<Meter> meters = meterRegistry.getMeters();
    assertThat(meters).hasSize(4);

    Collection<Gauge> gauges = meterRegistry.get(DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME)
        .gauges();

    Optional<Gauge> successful = findMeterByNamesTag(gauges, newRateLimiter.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newRateLimiter.getMetrics().getAvailablePermissions());
}
 
Example #7
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 #8
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 #9
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecoratorBuilderWithRateLimiter() {
    given(helloWorldService.returnHelloWorld()).willReturn("Hello world");
    RateLimiterConfig config = RateLimiterConfig.custom()
        .timeoutDuration(Duration.ofMillis(100))
        .limitRefreshPeriod(Duration.ofSeconds(1))
        .limitForPeriod(1)
        .build();
    RateLimiter rateLimiter = RateLimiter.of("backendName", config);
    CheckedFunction0<String> restrictedSupplier = Decorators
        .ofCheckedSupplier(() -> helloWorldService.returnHelloWorld())
        .withRateLimiter(rateLimiter)
        .decorate();
    alignTime(rateLimiter);

    Try<String> firstTry = Try.of(restrictedSupplier);
    Try<String> secondTry = Try.of(restrictedSupplier);

    assertThat(firstTry.isSuccess()).isTrue();
    assertThat(secondTry.isFailure()).isTrue();
    assertThat(secondTry.getCause()).isInstanceOf(RequestNotPermitted.class);
    then(helloWorldService).should(times(1)).returnHelloWorld();
}
 
Example #10
Source File: RateLimitersHealthIndicator.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
private Health mapRateLimiterHealth(RateLimiter rateLimiter) {
    RateLimiter.Metrics metrics = rateLimiter.getMetrics();
    int availablePermissions = metrics.getAvailablePermissions();
    int numberOfWaitingThreads = metrics.getNumberOfWaitingThreads();
    long timeoutInNanos = rateLimiter.getRateLimiterConfig().getTimeoutDuration().toNanos();

    if (availablePermissions > 0 || numberOfWaitingThreads == 0) {
        return rateLimiterHealth(Status.UP, availablePermissions, numberOfWaitingThreads);
    }

    if (rateLimiter instanceof AtomicRateLimiter) {
        AtomicRateLimiter atomicRateLimiter = (AtomicRateLimiter) rateLimiter;
        AtomicRateLimiter.AtomicRateLimiterMetrics detailedMetrics = atomicRateLimiter
            .getDetailedMetrics();
        if (detailedMetrics.getNanosToWait() > timeoutInNanos) {
            boolean allowHealthIndicatorToFail = allowHealthIndicatorToFail(rateLimiter);

            return rateLimiterHealth(allowHealthIndicatorToFail ? Status.DOWN : new Status("RATE_LIMITED"), availablePermissions, numberOfWaitingThreads);
        }
    }
    return rateLimiterHealth(Status.UNKNOWN, availablePermissions, numberOfWaitingThreads);
}
 
Example #11
Source File: SemaphoreBasedRateLimiterImplTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void changeDefaultTimeoutDuration() throws Exception {
    ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class);
    RateLimiter rateLimiter = new SemaphoreBasedRateLimiter("some", config,
        scheduledExecutorService);
    RateLimiterConfig rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(TIMEOUT);
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(LIMIT);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(REFRESH_PERIOD);

    rateLimiter.changeTimeoutDuration(Duration.ofSeconds(1));
    then(rateLimiterConfig != rateLimiter.getRateLimiterConfig()).isTrue();
    rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(Duration.ofSeconds(1));
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(LIMIT);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(REFRESH_PERIOD);
}
 
Example #12
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 #13
Source File: TaggedRateLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddMetricsForANewlyCreatedRateLimiter() {
    RateLimiter newRateLimiter = rateLimiterRegistry.rateLimiter("backendB");

    assertThat(taggedRateLimiterMetricsPublisher.meterIdMap)
        .containsKeys("backendA", "backendB");
    assertThat(taggedRateLimiterMetricsPublisher.meterIdMap.get("backendA")).hasSize(2);
    assertThat(taggedRateLimiterMetricsPublisher.meterIdMap.get("backendB")).hasSize(2);

    List<Meter> meters = meterRegistry.getMeters();
    assertThat(meters).hasSize(4);

    Collection<Gauge> gauges = meterRegistry.get(DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME)
        .gauges();

    Optional<Gauge> successful = findMeterByNamesTag(gauges, newRateLimiter.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newRateLimiter.getMetrics().getAvailablePermissions());
}
 
Example #14
Source File: InMemoryRateLimiterRegistry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RateLimiter rateLimiter(String name, String configName,
    io.vavr.collection.Map<String, String> tags) {
    return computeIfAbsent(name, () -> RateLimiter.of(name, getConfiguration(configName)
        .orElseThrow(() -> new ConfigurationNotFoundException(configName)), getAllTags(tags)));
}
 
Example #15
Source File: RateLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected RateLimiter givenMetricRegistry(String prefix, MetricRegistry metricRegistry) {
    RateLimiterRegistry rateLimiterRegistry =
        RateLimiterRegistry.of(RateLimiterConfig.ofDefaults(),
            new RateLimiterMetricsPublisher(prefix, metricRegistry));

    return rateLimiterRegistry.rateLimiter("testLimit");
}
 
Example #16
Source File: InMemoryRateLimiterRegistry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RateLimiter rateLimiter(String name,
    Supplier<RateLimiterConfig> rateLimiterConfigSupplier,
    io.vavr.collection.Map<String, String> tags) {
    return computeIfAbsent(name, () -> new AtomicRateLimiter(name, Objects.requireNonNull(
        Objects.requireNonNull(rateLimiterConfigSupplier, SUPPLIER_MUST_NOT_BE_NULL).get(),
        CONFIG_MUST_NOT_BE_NULL), getAllTags(tags)));
}
 
Example #17
Source File: AbstractRateLimiterConfigurationOnMissingBean.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public RegistryEventConsumer<RateLimiter> rateLimiterRegistryEventConsumer(
    Optional<List<RegistryEventConsumer<RateLimiter>>> optionalRegistryEventConsumers) {
    return rateLimiterConfiguration
        .rateLimiterRegistryEventConsumer(optionalRegistryEventConsumers);
}
 
Example #18
Source File: InMemoryRateLimiterRegistry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RateLimiter rateLimiter(String name, RateLimiterConfig config,
    io.vavr.collection.Map<String, String> tags) {
    return computeIfAbsent(name, () -> new AtomicRateLimiter(name,
        Objects.requireNonNull(config, CONFIG_MUST_NOT_BE_NULL), getAllTags(tags)));
}
 
Example #19
Source File: TaggedRateLimiterMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddCustomTags() {
    RateLimiter newRateLimiter = rateLimiterRegistry.rateLimiter("backendF", io.vavr.collection.HashMap.of("key1", "value1"));
    assertThat(taggedRateLimiterMetrics.meterIdMap).containsKeys("backendA", "backendF");
    assertThat(taggedRateLimiterMetrics.meterIdMap.get("backendA")).hasSize(2);
    assertThat(taggedRateLimiterMetrics.meterIdMap.get("backendF")).hasSize(2);
    List<Meter> meters = meterRegistry.getMeters();
    assertThat(meters).hasSize(4);
    assertThat(meterRegistry.get(DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME).tag("key1", "value1")).isNotNull();
}
 
Example #20
Source File: RateLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected RateLimiter givenMetricRegistry(MetricRegistry metricRegistry) {
    RateLimiterRegistry rateLimiterRegistry =
        RateLimiterRegistry.of(RateLimiterConfig.ofDefaults(),
            new RateLimiterMetricsPublisher(metricRegistry));

    return rateLimiterRegistry.rateLimiter("testLimit");
}
 
Example #21
Source File: RateLimiterConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a rate limiter registry.
 *
 * @param rateLimiterConfigurationProperties The rate limiter configuration properties.
 * @param compositeRateLimiterCustomizer the composite rate limiter customizer delegate
 * @return a RateLimiterRegistry
 */
private RateLimiterRegistry createRateLimiterRegistry(
    RateLimiterConfigurationProperties rateLimiterConfigurationProperties,
    RegistryEventConsumer<RateLimiter> rateLimiterRegistryEventConsumer,
    CompositeCustomizer<RateLimiterConfigCustomizer> compositeRateLimiterCustomizer) {
    Map<String, RateLimiterConfig> configs = rateLimiterConfigurationProperties.getConfigs()
        .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            entry -> rateLimiterConfigurationProperties
                .createRateLimiterConfig(entry.getValue(), compositeRateLimiterCustomizer,
                    entry.getKey())));

    return RateLimiterRegistry.of(configs, rateLimiterRegistryEventConsumer,
        io.vavr.collection.HashMap.ofAll(rateLimiterConfigurationProperties.getTags()));
}
 
Example #22
Source File: RateLimiterConfigurationTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testRateLimiterRegistry() {
    io.github.resilience4j.common.ratelimiter.configuration.RateLimiterConfigurationProperties.InstanceProperties instanceProperties1 = new io.github.resilience4j.common.ratelimiter.configuration.RateLimiterConfigurationProperties.InstanceProperties();
    instanceProperties1.setLimitForPeriod(2);
    instanceProperties1.setSubscribeForEvents(true);
    io.github.resilience4j.common.ratelimiter.configuration.RateLimiterConfigurationProperties.InstanceProperties instanceProperties2 = new io.github.resilience4j.common.ratelimiter.configuration.RateLimiterConfigurationProperties.InstanceProperties();
    instanceProperties2.setLimitForPeriod(4);
    instanceProperties2.setSubscribeForEvents(true);
    RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties();
    rateLimiterConfigurationProperties.getInstances().put("backend1", instanceProperties1);
    rateLimiterConfigurationProperties.getInstances().put("backend2", instanceProperties2);
    rateLimiterConfigurationProperties.setRateLimiterAspectOrder(300);
    RateLimiterConfiguration rateLimiterConfiguration = new RateLimiterConfiguration();
    DefaultEventConsumerRegistry<RateLimiterEvent> eventConsumerRegistry = new DefaultEventConsumerRegistry<>();

    RateLimiterRegistry rateLimiterRegistry = rateLimiterConfiguration
        .rateLimiterRegistry(rateLimiterConfigurationProperties, eventConsumerRegistry,
            new CompositeRegistryEventConsumer<>(emptyList()),
            compositeRateLimiterCustomizerTest());

    assertThat(rateLimiterConfigurationProperties.getRateLimiterAspectOrder()).isEqualTo(300);
    assertThat(rateLimiterRegistry.getAllRateLimiters().size()).isEqualTo(2);
    RateLimiter rateLimiter = rateLimiterRegistry.rateLimiter("backend1");
    assertThat(rateLimiter).isNotNull();
    assertThat(rateLimiter.getRateLimiterConfig().getLimitForPeriod()).isEqualTo(2);
    RateLimiter rateLimiter2 = rateLimiterRegistry.rateLimiter("backend2");
    assertThat(rateLimiter2).isNotNull();
    assertThat(rateLimiter2.getRateLimiterConfig().getLimitForPeriod()).isEqualTo(4);
    assertThat(eventConsumerRegistry.getAllEventConsumer()).hasSize(2);
}
 
Example #23
Source File: RateLimiterMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected RateLimiter givenMetricRegistry(MetricRegistry metricRegistry) {
    RateLimiterRegistry rateLimiterRegistry = RateLimiterRegistry.ofDefaults();
    RateLimiter rateLimiter = rateLimiterRegistry.rateLimiter("testLimit");
    metricRegistry.registerAll(RateLimiterMetrics.ofRateLimiterRegistry(rateLimiterRegistry));

    return rateLimiter;
}
 
Example #24
Source File: SemaphoreBasedRateLimiterImplTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void getMetrics() throws Exception {
    ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
    SemaphoreBasedRateLimiter limit = new SemaphoreBasedRateLimiter("test", config, scheduler);
    RateLimiter.Metrics metrics = limit.getMetrics();
    then(metrics.getNumberOfWaitingThreads()).isEqualTo(0);
}
 
Example #25
Source File: RateLimiterConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private void registerEventConsumer(
    EventConsumerRegistry<RateLimiterEvent> eventConsumerRegistry, RateLimiter rateLimiter,
    RateLimiterConfigurationProperties rateLimiterConfigurationProperties) {
    final io.github.resilience4j.common.ratelimiter.configuration.RateLimiterConfigurationProperties.InstanceProperties limiterProperties = rateLimiterConfigurationProperties
        .getInstances().get(rateLimiter.getName());
    if (limiterProperties != null && limiterProperties.getSubscribeForEvents() != null
        && limiterProperties.getSubscribeForEvents()) {
        rateLimiter.getEventPublisher().onEvent(eventConsumerRegistry
            .createEventConsumer(rateLimiter.getName(),
                limiterProperties.getEventConsumerBufferSize() != null
                    && limiterProperties.getEventConsumerBufferSize() != 0 ? limiterProperties
                    .getEventConsumerBufferSize() : 100));
    }
}
 
Example #26
Source File: SemaphoreBasedRateLimiterImplTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void getDetailedMetrics() throws Exception {
    ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
    SemaphoreBasedRateLimiter limit = new SemaphoreBasedRateLimiter("test", config, scheduler);
    RateLimiter.Metrics metrics = limit.getMetrics();
    then(metrics.getNumberOfWaitingThreads()).isEqualTo(0);
    then(metrics.getAvailablePermissions()).isEqualTo(2);
}
 
Example #27
Source File: InMemoryRateLimiterRegistryTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void rateLimiterPositive() throws Exception {
    RateLimiterRegistry registry = RateLimiterRegistry.of(config);
    RateLimiter firstRateLimiter = registry.rateLimiter("test");
    RateLimiter anotherLimit = registry.rateLimiter("test1");
    RateLimiter sameAsFirst = registry.rateLimiter("test");

    then(firstRateLimiter).isEqualTo(sameAsFirst);
    then(firstRateLimiter).isNotEqualTo(anotherLimit);
}
 
Example #28
Source File: RxJava2RateLimiterAspectExt.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * @param proceedingJoinPoint Spring AOP proceedingJoinPoint
 * @param rateLimiter         the configured rateLimiter
 * @param methodName          the method name
 * @return the result object
 * @throws Throwable exception in case of faulty flow
 */
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter,
    String methodName) throws Throwable {
    RateLimiterOperator<?> rateLimiterOperator = RateLimiterOperator.of(rateLimiter);
    Object returnValue = proceedingJoinPoint.proceed();
    return executeRxJava2Aspect(rateLimiterOperator, returnValue);
}
 
Example #29
Source File: ReactorRateLimiterAspectExtTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testReactorTypes() throws Throwable {
    RateLimiter rateLimiter = RateLimiter.ofDefaults("test");

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

    when(proceedingJoinPoint.proceed()).thenReturn(Flux.just("Test"));
    assertThat(
        reactorRateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod"))
        .isNotNull();
}
 
Example #30
Source File: RateLimiterMetricsPublisher.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public void publishMetrics(RateLimiter rateLimiter) {
    String name = rateLimiter.getName();

    String waitingThreads = name(prefix, name, WAITING_THREADS);
    String availablePermissions = name(prefix, name, AVAILABLE_PERMISSIONS);

    metricRegistry.register(waitingThreads,
        (Gauge<Integer>) rateLimiter.getMetrics()::getNumberOfWaitingThreads);
    metricRegistry.register(availablePermissions,
        (Gauge<Integer>) rateLimiter.getMetrics()::getAvailablePermissions);

    List<String> metricNames = Arrays.asList(waitingThreads, availablePermissions);
    metricsNameMap.put(name, new HashSet<>(metricNames));
}