io.github.resilience4j.ratelimiter.RateLimiterConfig Java Examples

The following examples show how to use io.github.resilience4j.ratelimiter.RateLimiterConfig. 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: AtomicRateLimiterTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void changeDefaultTimeoutDuration() throws Exception {
    setup(Duration.ZERO);

    RateLimiterConfig rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(Duration.ZERO);
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(PERMISSIONS_RER_CYCLE);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(Duration.ofNanos(CYCLE_IN_NANOS));

    rateLimiter.changeTimeoutDuration(Duration.ofSeconds(1));
    then(rateLimiterConfig != rateLimiter.getRateLimiterConfig()).isTrue();
    rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(Duration.ofSeconds(1));
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(PERMISSIONS_RER_CYCLE);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(Duration.ofNanos(CYCLE_IN_NANOS));
}
 
Example #2
Source File: RateLimitingInterceptor.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (!shouldRateLimit(request)) {
        return true;
    }
    String ipAddress = request.getRemoteAddr();
    AtomicRateLimiter rateLimiter = rateLimiterProvider.getRateLimiter(ipAddress);

    boolean hasAcquiredPermission = rateLimiter.acquirePermission();
    AtomicRateLimiterMetrics metrics = rateLimiter.getDetailedMetrics();
    RateLimiterConfig config = rateLimiter.getRateLimiterConfig();

    response.setHeader(Constants.RATE_LIMIT, Integer.toString(config.getLimitForPeriod()));
    response.setHeader(Constants.RATE_LIMIT_REMAINING, Integer.toString(metrics.getAvailablePermissions()));

    if (!hasAcquiredPermission) {
        response.setHeader(Constants.RATE_LIMIT_RESET, Long.toString(getUtcTimeForNextReset(metrics.getNanosToWait())));
        response.sendError(HttpStatus.TOO_MANY_REQUESTS.value(), HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
        return false;
    }
    return true;
}
 
Example #3
Source File: RateLimiterRegistry.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
private static RateLimiterConfig createRateLimiterConfig(FormulaRateLimiterConfig rateLimiterConfig) {
    if (rateLimiterConfig == null) {
        return null;
    }

    RateLimiterConfig.Builder rateLimiterConfigBuilder = RateLimiterConfig.custom();

    if (rateLimiterConfig.getThreshold() != null) {
        rateLimiterConfigBuilder.limitForPeriod(rateLimiterConfig.getThreshold());
    }

    // rateLimiterConfigBuilder.limitRefreshPeriod(Duration.ofMillis(1000)); // default 1s

    if (rateLimiterConfig.getTimeoutInMillis() != null) { // default 0
        rateLimiterConfigBuilder.timeoutDuration(Duration.ofMillis(rateLimiterConfig.getTimeoutInMillis()));
    }

    return rateLimiterConfigBuilder.build();
}
 
Example #4
Source File: RateLimiterConfigurationProperties.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
public RateLimiterConfig createRateLimiterConfig(
    @Nullable InstanceProperties instanceProperties,
    CompositeCustomizer<RateLimiterConfigCustomizer> compositeRateLimiterCustomizer,
    String instanceName) {
    if (instanceProperties == null) {
        return RateLimiterConfig.ofDefaults();
    }
    if (StringUtils.isNotEmpty(instanceProperties.getBaseConfig())) {
        InstanceProperties baseProperties = configs.get(instanceProperties.baseConfig);
        if (baseProperties == null) {
            throw new ConfigurationNotFoundException(instanceProperties.getBaseConfig());
        }
        return buildConfigFromBaseConfig(baseProperties, instanceProperties,
            compositeRateLimiterCustomizer, instanceName);
    }
    return buildRateLimiterConfig(RateLimiterConfig.custom(), instanceProperties,
        compositeRateLimiterCustomizer, instanceName);
}
 
Example #5
Source File: SemaphoreBasedRateLimiter.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a RateLimiter.
 *
 * @param name              the name of the RateLimiter
 * @param rateLimiterConfig The RateLimiter configuration.
 * @param scheduler         executor that will refresh permissions
 * @param tags              tags to assign to the RateLimiter
 */
public SemaphoreBasedRateLimiter(String name, RateLimiterConfig rateLimiterConfig,
    @Nullable ScheduledExecutorService scheduler, Map<String, String> tags) {
    this.name = requireNonNull(name, NAME_MUST_NOT_BE_NULL);
    this.rateLimiterConfig = new AtomicReference<>(
        requireNonNull(rateLimiterConfig, CONFIG_MUST_NOT_BE_NULL));

    this.scheduler = Option.of(scheduler).getOrElse(this::configureScheduler);
    this.tags = tags;
    this.semaphore = new Semaphore(this.rateLimiterConfig.get().getLimitForPeriod(), true);
    this.metrics = this.new SemaphoreBasedRateLimiterMetrics();

    this.eventProcessor = new RateLimiterEventProcessor();

    scheduleLimitRefresh();
}
 
Example #6
Source File: AtomicRateLimiterTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void changeLimitForPeriod() throws Exception {
    setup(Duration.ZERO);

    RateLimiterConfig rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(Duration.ZERO);
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(PERMISSIONS_RER_CYCLE);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(Duration.ofNanos(CYCLE_IN_NANOS));

    rateLimiter.changeLimitForPeriod(35);
    then(rateLimiterConfig != rateLimiter.getRateLimiterConfig()).isTrue();
    rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(Duration.ZERO);
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(35);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(Duration.ofNanos(CYCLE_IN_NANOS));
}
 
Example #7
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 #8
Source File: SemaphoreBasedRateLimiterImplTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void changeLimitForPeriod() 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.changeLimitForPeriod(LIMIT * 2);
    then(rateLimiterConfig != rateLimiter.getRateLimiterConfig()).isTrue();
    rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(TIMEOUT);
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(LIMIT * 2);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(REFRESH_PERIOD);
}
 
Example #9
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 #10
Source File: RateLimitersImplementationTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
protected void waitForRefresh(RateLimiter.Metrics metrics, RateLimiterConfig config,
                              char printedWhileWaiting) {
    Instant start = Instant.now();
    while (Instant.now().isBefore(start.plus(config.getLimitRefreshPeriod()))) {
        try {
            if (metrics.getAvailablePermissions() == config.getLimitForPeriod()) {
                break;
            }
            System.out.print(printedWhileWaiting);
            Thread.sleep(10);
        } catch (InterruptedException ex) {
            throw new IllegalStateException(ex);
        }
    }
    System.out.println();
}
 
Example #11
Source File: TaggedRateLimiterMetricsPublisherTest.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 #12
Source File: TaggedRateLimiterMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void customMetricNamesGetApplied() {
    MeterRegistry meterRegistry = new SimpleMeterRegistry();
    TaggedRateLimiterMetricsPublisher taggedRateLimiterMetricsPublisher = new TaggedRateLimiterMetricsPublisher(
        RateLimiterMetricNames.custom()
            .availablePermissionsMetricName("custom_available_permissions")
            .waitingThreadsMetricName("custom_waiting_threads")
            .build(), meterRegistry);

    RateLimiterRegistry rateLimiterRegistry = RateLimiterRegistry
        .of(RateLimiterConfig.ofDefaults(), taggedRateLimiterMetricsPublisher);
    rateLimiterRegistry.rateLimiter("backendA");

    Set<String> metricNames = meterRegistry.getMeters()
        .stream()
        .map(Meter::getId)
        .map(Meter.Id::getName)
        .collect(Collectors.toSet());

    assertThat(metricNames).hasSameElementsAs(Arrays.asList(
        "custom_available_permissions",
        "custom_waiting_threads"
    ));
}
 
Example #13
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 #14
Source File: RateLimiterAspect.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
private io.github.resilience4j.ratelimiter.RateLimiter getOrCreateRateLimiter(String methodName,
    String name) {
    io.github.resilience4j.ratelimiter.RateLimiter rateLimiter = rateLimiterRegistry
        .rateLimiter(name);

    if (logger.isDebugEnabled()) {
        RateLimiterConfig rateLimiterConfig = rateLimiter.getRateLimiterConfig();
        logger.debug(
            RATE_LIMITER_RECEIVED,
            name, rateLimiterConfig.getLimitRefreshPeriod(),
            rateLimiterConfig.getLimitForPeriod(),
            rateLimiterConfig.getTimeoutDuration(), methodName
        );
    }

    return rateLimiter;
}
 
Example #15
Source File: RetrofitRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@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(RateLimiterCallAdapter.of(RateLimiter.of(
            "backendName",
            RateLimiterConfig.custom()
                .timeoutDuration(Duration.ofMillis(50))
                .limitForPeriod(1)
                .limitRefreshPeriod(Duration.ofDays(1))
                .build()
        )))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .client(client)
        .baseUrl(wireMockRule.baseUrl())
        .build()
        .create(RetrofitService.class);

    Single<String> success = service.delegated();
    Single<String> failure = service.delegated();

    String resultBody = success.blockingGet();
    try {
        failure.blockingGet();
        fail("Expected HttpException to be thrown");
    } catch (HttpException httpe) {
        assertThat(httpe.code()).isEqualTo(429);
    }

    assertThat(resultBody).isEqualTo(body);
    verify(1, getRequestedFor(urlPathEqualTo("/delegated")));
}
 
Example #16
Source File: RateLimiterRegistry.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
protected RateLimiter rateLimiter(String name, RateLimiterConfig rateLimiterConfig, Integer limiterType) {
    requireNonNull(name, NAME_MUST_NOT_BE_NULL);
    requireNonNull(rateLimiterConfig, CONFIG_MUST_NOT_BE_NULL);
    return rateLimiters.computeIfAbsent(
            name,
            limitName -> {
                switch (limiterType) {
                    case 1: return new TokenBucketRateLimiter(name, rateLimiterConfig);
                    case 2: return new SemaphoreBasedRateLimiter(name, rateLimiterConfig);
                }
                return null;
            }
    );
}
 
Example #17
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 #18
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 #19
Source File: TokenBucketRateLimiterTest.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    limitsForPeriod = 2;
    RateLimiterConfig.Builder rateLimiterConfigBuilder = RateLimiterConfig.custom();
    rateLimiterConfigBuilder.limitForPeriod(limitsForPeriod);
    rateLimiterConfig = rateLimiterConfigBuilder.build();
}
 
Example #20
Source File: InMemoryRateLimiterRegistryTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    config = RateLimiterConfig.custom()
        .timeoutDuration(TIMEOUT)
        .limitRefreshPeriod(REFRESH_PERIOD)
        .limitForPeriod(LIMIT)
        .build();
}
 
Example #21
Source File: SemaphoreBasedRateLimiterImplTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void acquirePermissionInterruption() throws Exception {
    ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class);
    RateLimiterConfig configSpy = spy(config);
    SemaphoreBasedRateLimiter limit = new SemaphoreBasedRateLimiter("test", configSpy,
        scheduledExecutorService);
    assertThat(limit.getName()).isEqualTo("test");
    limit.acquirePermission();
    limit.acquirePermission();

    Thread thread = new Thread(() -> {
        limit.acquirePermission();
        while (true) {
            Function.identity().apply(1);
        }
    });
    thread.setDaemon(true);
    thread.start();

    awaitImpatiently()
        .atMost(2, TimeUnit.SECONDS).until(thread::getState, equalTo(TIMED_WAITING));

    thread.interrupt();

    awaitImpatiently()
        .atMost(2, TimeUnit.SECONDS).until(thread::getState, equalTo(RUNNABLE));
    awaitImpatiently()
        .atMost(100, TimeUnit.MILLISECONDS).until(thread::isInterrupted);
}
 
Example #22
Source File: SemaphoreBasedRateLimiterImplTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void rateLimiterCreationWithProvidedScheduler() throws Exception {
    ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class);
    RateLimiterConfig configSpy = spy(config);
    SemaphoreBasedRateLimiter limit = new SemaphoreBasedRateLimiter("test", configSpy,
        scheduledExecutorService);

    ArgumentCaptor<Runnable> refreshLimitRunnableCaptor = ArgumentCaptor
        .forClass(Runnable.class);
    verify(scheduledExecutorService)
        .scheduleAtFixedRate(
            refreshLimitRunnableCaptor.capture(),
            eq(config.getLimitRefreshPeriod().toNanos()),
            eq(config.getLimitRefreshPeriod().toNanos()),
            eq(TimeUnit.NANOSECONDS)
        );

    Runnable refreshLimitRunnable = refreshLimitRunnableCaptor.getValue();

    then(limit.acquirePermission()).isTrue();
    then(limit.acquirePermission()).isTrue();
    then(limit.acquirePermission()).isFalse();

    Thread.sleep(REFRESH_PERIOD.toMillis() * 2);
    verify(configSpy, times(1)).getLimitForPeriod();

    refreshLimitRunnable.run();

    verify(configSpy, times(2)).getLimitForPeriod();

    then(limit.acquirePermission()).isTrue();
    then(limit.acquirePermission()).isTrue();
    then(limit.acquirePermission()).isFalse();

}
 
Example #23
Source File: SemaphoreBasedRateLimiterImplTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    config = RateLimiterConfig.custom()
        .timeoutDuration(TIMEOUT)
        .limitRefreshPeriod(REFRESH_PERIOD)
        .limitForPeriod(LIMIT)
        .build();
}
 
Example #24
Source File: Resilience4jFeignRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test(expected = RequestNotPermitted.class)
public void testRateLimiterLimiting() {
    givenResponse(200);
    when(rateLimiter.acquirePermission(1)).thenReturn(false);
    when(rateLimiter.getRateLimiterConfig()).thenReturn(RateLimiterConfig.ofDefaults());

    testService.greeting();

    verify(0, getRequestedFor(urlPathEqualTo("/greeting")));
}
 
Example #25
Source File: AtomicRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void notSpyRawNonBlockingTest() {
    RateLimiterConfig rateLimiterConfig = RateLimiterConfig.custom()
        .limitForPeriod(PERMISSIONS_RER_CYCLE)
        .limitRefreshPeriod(Duration.ofNanos(CYCLE_IN_NANOS))
        .timeoutDuration(Duration.ZERO)
        .build();

    AtomicRateLimiter rawLimiter = new AtomicRateLimiter("rawLimiter", rateLimiterConfig);
    AtomicRateLimiter.AtomicRateLimiterMetrics rawDetailedMetrics = rawLimiter
        .getDetailedMetrics();

    long firstCycle = waitForCurrentCycleToPass(rawDetailedMetrics, '.');

    long firstPermission = rawLimiter.reservePermission();
    waitForPermissionRenewal(rawDetailedMetrics, '*');

    long secondPermission = rawLimiter.reservePermission();
    long firstNoPermission = rawLimiter.reservePermission();
    long secondCycle = rawDetailedMetrics.getCycle();

    rawLimiter.changeLimitForPeriod(PERMISSIONS_RER_CYCLE * 2);
    waitForPermissionRenewal(rawDetailedMetrics, '^');
    long thirdPermission = rawLimiter.reservePermission();
    long fourthPermission = rawLimiter.reservePermission();
    long secondNoPermission = rawLimiter.reservePermission();
    long thirdCycle = rawDetailedMetrics.getCycle();

    then(secondCycle - firstCycle).isEqualTo(2);
    then(thirdCycle - secondCycle).isEqualTo(1);

    then(firstPermission).isZero();
    then(secondPermission).isZero();
    then(thirdPermission).isZero();
    then(fourthPermission).isZero();

    then(firstNoPermission).isNegative();
    then(secondNoPermission).isNegative();
}
 
Example #26
Source File: AtomicRateLimiter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void changeTimeoutDuration(final Duration timeoutDuration) {
    RateLimiterConfig newConfig = RateLimiterConfig.from(state.get().config)
        .timeoutDuration(timeoutDuration)
        .build();
    state.updateAndGet(currentState -> new State(
        newConfig, currentState.activeCycle, currentState.activePermissions,
        currentState.nanosToWait
    ));
}
 
Example #27
Source File: AtomicRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public void setup(Duration cycleDuration, Duration timeoutDuration, int permissionPerCycle) {
    RateLimiterConfig rateLimiterConfig = RateLimiterConfig.custom()
        .limitForPeriod(permissionPerCycle)
        .limitRefreshPeriod(cycleDuration)
        .timeoutDuration(timeoutDuration)
        .build();
    AtomicRateLimiter testLimiter = new AtomicRateLimiter(LIMITER_NAME, rateLimiterConfig);
    rateLimiter = PowerMockito.spy(testLimiter);
    metrics = rateLimiter.getDetailedMetrics();
}
 
Example #28
Source File: SemaphoreBasedRateLimiter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void changeLimitForPeriod(int limitForPeriod) {
    RateLimiterConfig newConfig = RateLimiterConfig.from(rateLimiterConfig.get())
        .limitForPeriod(limitForPeriod)
        .build();
    rateLimiterConfig.set(newConfig);
}
 
Example #29
Source File: SemaphoreBasedRateLimiter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void changeTimeoutDuration(Duration timeoutDuration) {
    RateLimiterConfig newConfig = RateLimiterConfig.from(rateLimiterConfig.get())
        .timeoutDuration(timeoutDuration)
        .build();
    rateLimiterConfig.set(newConfig);
}
 
Example #30
Source File: InMemoryRateLimiterRegistryTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void rateLimiterNewWithNullConfigSupplier() throws Exception {
    exception.expect(NullPointerException.class);
    exception.expectMessage("Supplier must not be null");
    RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
    Supplier<RateLimiterConfig> rateLimiterConfigSupplier = null;
    registry.rateLimiter("name", rateLimiterConfigSupplier);
}