一、基本使用
1.1 创建限流器
/**
* Returns rate limiter instance by name
*
* @param name of rate limiter
* @return RateLimiter object
*/
RRateLimiter getRateLimiter(String name);
/**
* Initializes RateLimiter's state and stores config to Redis server.
*
* @param mode - rate mode
* @param rate - rate
* @param rateInterval - rate time interval
* @param rateIntervalUnit - rate time interval unit
* @return true if rate was set and false otherwise
*/
boolean trySetRate(RateType mode, long rate, long rateInterval, RateIntervalUnit rateIntervalUnit);
trySetRate
用于设置限流参数。其中 RateType 包含 OVERALL
和 PER_CLIENT
两个枚举常量,分别表示全局限流和单机限流。后面三个参数表明了令牌的生成速率,即每 rateInterval
生成 rate
个令牌,rateIntervalUnit
为 rateInterval
的时间单位。
1.2 获取令牌
/**
* Acquires a specified permits from this RateLimiter,
* blocking until one is available.
*
* Acquires the given number of permits, if they are available
* and returns immediately, reducing the number of available permits
* by the given amount.
*
* @param permits the number of permits to acquire
*/
void acquire(long permits);
/**
* Acquires the given number of permits only if all are available
* within the given waiting time.
*
* Acquires the given number of permits, if all are available and returns immediately,
* with the value true, reducing the number of available permits by one.
*
* If no permit is available then the current thread becomes
* disabled for thread scheduling purposes and lies dormant until
* the specified waiting time elapses.
*
* If a permits is acquired then the value true is returned.
*
* If the specified waiting time elapses then the value false
* is returned. If the time is less than or equal to zero, the method
* will not wait at all.
*
* @param permits amount
* @param timeout the maximum time to wait for a permit
* @param unit the time unit of the timeout argument
* @return true if a permit was acquired and false
* if the waiting time elapsed before a permit was acquired
*/
boolean tryAcquire(long permits, long timeout, TimeUnit unit);
acquire
和 tryAcquire
均可用于获取指定数量的令牌,不过 acquire
会阻塞等待,而 tryAcquire
会等待 timeout
时间,如果仍然没有获得指定数量的令牌直接返回 false
。
1.3 使用示例
@Slf4j
@SpringBootTest
class RateLimiterTest {
@Autowired
private RedissonClient redissonClient;
private static final int threadCount = 10;
@Test
void test() throws InterruptedException {
RRateLimiter rateLimiter = redissonClient.getRateLimiter("my_limiter");
rateLimiter.trySetRate(RateType.OVERALL, 10, 1, RateIntervalUnit.SECONDS);
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
new Thread(() -> {
rateLimiter.tryAcquire(5, 3, Ti