From ec5fcaa76b003e30daecf8a9d8aad251a6e171bb Mon Sep 17 00:00:00 2001 From: Looly Date: Mon, 19 Aug 2024 22:44:33 +0800 Subject: [PATCH] add RateLimiter --- .../ratelimiter/SemaphoreRateLimiterTest.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 hutool-core/src/test/java/org/dromara/hutool/core/thread/ratelimiter/SemaphoreRateLimiterTest.java diff --git a/hutool-core/src/test/java/org/dromara/hutool/core/thread/ratelimiter/SemaphoreRateLimiterTest.java b/hutool-core/src/test/java/org/dromara/hutool/core/thread/ratelimiter/SemaphoreRateLimiterTest.java new file mode 100644 index 000000000..a11b7f8f9 --- /dev/null +++ b/hutool-core/src/test/java/org/dromara/hutool/core/thread/ratelimiter/SemaphoreRateLimiterTest.java @@ -0,0 +1,27 @@ +package org.dromara.hutool.core.thread.ratelimiter; + +import org.dromara.hutool.core.thread.ThreadUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class SemaphoreRateLimiterTest { + + @Test + void test() { + final RateLimiterConfig rateLimiterConfig = RateLimiterConfig.of(5000, 300, 5); + final RateLimiter rateLimiter = new SemaphoreRateLimiter(rateLimiterConfig); + + final boolean b = rateLimiter.tryAcquire(5); + Assertions.assertTrue(b); + // 超过数量 + final boolean b1 = rateLimiter.tryAcquire(1); + Assertions.assertFalse(b1); + ThreadUtil.sleep(310); + // 填充新的许可 + final boolean b2 = rateLimiter.tryAcquire(5); + Assertions.assertTrue(b2); + // 超过数量 + final boolean b3 = rateLimiter.tryAcquire(1); + Assertions.assertFalse(b3); + } +}