Skip to content

Instantly share code, notes, and snippets.

@xlucasdemelo
Created May 26, 2020 00:01
Show Gist options
  • Save xlucasdemelo/34fe7d31b8e11eb3dee5f3f031369311 to your computer and use it in GitHub Desktop.
Save xlucasdemelo/34fe7d31b8e11eb3dee5f3f031369311 to your computer and use it in GitHub Desktop.
@Test
public void rateLimiterTest() {
MockResponse mockResponse = new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json;charset=utf-8");
//Resilience4J configuration for RateLimiter
//Defining that only one request can happend in 100ms window
RateLimiterConfig config = RateLimiterConfig.custom()
.timeoutDuration(Duration.ofMillis(100))
.limitRefreshPeriod(Duration.ofSeconds(1))
.limitForPeriod(1)
.build();
// Create a RateLimiter
RateLimiter rateLimiter = RateLimiter.of("books", config);
//This only capture all the emmitted by the library
this.captureEvents(rateLimiter.getEventPublisher());
// Decorate your call to BackendService.doSomething()
Supplier<String> restrictedSupplier = RateLimiter
.decorateSupplier(rateLimiter, bookClient::findAll);
//THis prepares the mock server to mock 2 requests
this.enqueue(2, mockResponse);
// Try.ofSupplier will execute the decorated function above
Try<String> firstTry = Try.ofSupplier(restrictedSupplier);
//First call will be successful
Assertions.assertThat(firstTry.isSuccess()).isTrue();
// Second call fails, because the call was executed inside a 100ms window
Try<String> secondTry = Try.ofSupplier(restrictedSupplier);
Assertions.assertThat(secondTry.isFailure()).isTrue();
Assertions.assertThat(secondTry.getCause()).isInstanceOf(RequestNotPermitted.class);
// Asserting that the first call was successful, and thhe second one failed
Assertions.assertThat(this.events)
.extracting(RateLimiterEvent::getEventType)
.containsExactly(
RateLimiterEvent.Type.SUCCESSFUL_ACQUIRE,
RateLimiterEvent.Type.FAILED_ACQUIRE
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment