java代码实现redis 令牌桶限流
时间: 2024-01-03 20:23:04 浏览: 89
以下是基于Java和Redis实现令牌桶限流的代码示例:
```java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;
public class RedisTokenBucket {
private static final String REDIS_KEY = "token_bucket";
private static final int MAX_TOKENS = 100; // 令牌桶容量
private static final int REFILL_RATE = 10; // 每秒添加的令牌数
public boolean allowRequest() {
Jedis jedis = new Jedis("localhost"); // 连接本地的Redis服务器
try {
Transaction transaction = jedis.multi();
transaction.zremrangeByScore(REDIS_KEY, "-inf", String.valueOf(System.currentTimeMillis() - 1000));
Response<Long> countResponse = transaction.zcard(REDIS_KEY);
transaction.zadd(REDIS_KEY, System.currentTimeMillis(), String.valueOf(System.currentTimeMillis()));
transaction.zrange(REDIS_KEY, 0, -1);
transaction.expire(REDIS_KEY, 1);
transaction.exec();
long count = countResponse.get();
return count <= MAX_TOKENS;
} finally {
jedis.close();
}
}
}
```
该代码使用了Redis的有序集合(Sorted Set)来实现令牌桶限流。每个请求在处理之前都需要从令牌桶中获取一个令牌,只有拿到令牌才能进行其他的业务逻辑。令牌桶的容量为100,每秒添加10个令牌。当令牌桶满时,新的令牌会被丢弃或拒绝。
使用示例:
```java
public class Main {
public static void main(String[] args) {
RedisTokenBucket tokenBucket = new RedisTokenBucket();
for (int i = 0; i < 10; i++) {
if (tokenBucket.allowRequest()) {
System.out.println("Request " + (i + 1) + ": Allowed");
} else {
System.out.println("Request " + (i + 1) + ": Denied");
}
}
}
}
```
运行上述代码,将输出类似以下结果:
```
Request 1: Allowed
Request 2: Allowed
Request 3: Allowed
Request 4: Allowed
Request 5: Allowed
Request 6: Denied
Request 7: Denied
Request 8: Denied
Request 9: Denied
Request 10: Denied
```
阅读全文