Skip to content

Commit 46e8756

Browse files
committed
redis 限流
1 parent c6c821d commit 46e8756

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package org.cp.javaredis;
2+
3+
import java.time.LocalDateTime;
4+
import java.util.concurrent.TimeUnit;
5+
import org.junit.jupiter.api.Test;
6+
import org.redisson.api.RRateLimiter;
7+
import org.redisson.api.RateIntervalUnit;
8+
import org.redisson.api.RateType;
9+
import org.redisson.api.RedissonClient;
10+
import org.springframework.beans.factory.annotation.Autowired;
11+
import org.springframework.boot.test.context.SpringBootTest;
12+
13+
@SpringBootTest
14+
public class SimpleLimit {
15+
16+
@Autowired
17+
RedissonClient redissonClient;
18+
19+
@Test
20+
public void test() throws InterruptedException {
21+
// redisson用了zset来记录请求的信息,这样可以非常巧妙的通过比较score,也就是请求的时间戳,来判断当前请求距离上一个请求有没有超过一个令牌生产周期。如果超过了,则说明令牌桶中的令牌需要生产,之前用掉了多少个就生产多少个,而之前用掉了多少个令牌的信息也在zset中保存了。
22+
RRateLimiter limiter = redissonClient.getRateLimiter("limiter_1");
23+
// 1号限流器, 每一秒 允许一个请求
24+
limiter.trySetRate(RateType.PER_CLIENT, 1, 1, RateIntervalUnit.SECONDS);
25+
26+
for (int i = 0; i < 10; i++) {
27+
new Thread(() -> {
28+
29+
// 阻塞
30+
// limiter.acquire(1);
31+
32+
boolean result = limiter.tryAcquire(1, 100, TimeUnit.MILLISECONDS);
33+
if (!result) {
34+
// 快速失败
35+
System.out.println(Thread.currentThread().getName() + " failed !");
36+
return;
37+
}
38+
39+
System.out.println(Thread.currentThread().getName() + " -> " + LocalDateTime.now());
40+
// do something
41+
}).start();
42+
}
43+
44+
Thread.sleep(12000);
45+
}
46+
47+
}

0 commit comments

Comments
 (0)