redis限流java写法
时间: 2023-07-08 20:47:45 浏览: 118
Redis可以通过令牌桶算法实现限流。下面是Java代码示例:
首先,在pom.xml中添加Redis依赖:
```
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
```
然后,实现令牌桶算法的限流器:
```java
import redis.clients.jedis.Jedis;
public class RedisRateLimiter {
private Jedis jedis;
private String key;
private int limit;
private long interval;
public RedisRateLimiter(Jedis jedis, String key, int limit, long interval) {
this.jedis = jedis;
this.key = key;
this.limit = limit;
this.interval = interval;
}
public boolean acquire() {
long now = System.currentTimeMillis();
String lastTokenTime = jedis.get(key);
// 计算当前令牌数
int tokens = 0;
if (lastTokenTime != null) {
long timeElapsed = now - Long.parseLong(lastTokenTime);
tokens = (int) (timeElapsed / interval);
tokens = Math.min(tokens, limit); // 令牌数不能超过限流器的容量
}
// 如果令牌数大于0,则允许访问,并更新令牌数和最后一个令牌的时间戳
if (tokens > 0) {
jedis.set(key, String.valueOf(now));
return true;
}
// 令牌数为0,则不允许访问
return false;
}
}
```
最后,使用限流器进行限流:
```java
import redis.clients.jedis.Jedis;
public class Main {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
RedisRateLimiter rateLimiter = new RedisRateLimiter(jedis, "my-limiter", 10, 1000); // 限流器容量为10,每秒放入1个令牌
for (int i = 0; i < 20; i++) {
if (rateLimiter.acquire()) {
System.out.println("访问成功");
} else {
System.out.println("访问失败");
}
}
jedis.close();
}
}
```
这段代码中,限流器的容量为10,每秒放入1个令牌。在20次访问中,前10次会成功,后10次会失败。
阅读全文