redis限流java写法
时间: 2023-05-12 18:07:03 浏览: 108
java-基于redis限流系统
5星 · 资源好评率100%
Redis限流可以使用令牌桶算法实现,Java代码如下:
```java
public class RedisRateLimiter {
private final Jedis jedis;
private final String key;
private final int capacity;
private final int rate;
private final long interval;
public RedisRateLimiter(Jedis jedis, String key, int capacity, int rate, long interval) {
this.jedis = jedis;
this.key = key;
this.capacity = capacity;
this.rate = rate;
this.interval = interval;
}
public boolean acquire() {
long now = System.currentTimeMillis();
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.zremrangeByScore(key, 0, now - interval);
pipeline.zcard(key);
Response<Long> countResponse = pipeline.zadd(key, now, String.valueOf(now));
pipeline.expire(key, interval / 1000);
pipeline.exec();
pipeline.sync();
long count = countResponse.get();
return count <= capacity && count > rate;
}
}
```
其中,jedis是Redis客户端,key是限流的键名,capacity是桶的容量,rate是每秒放入桶中的令牌数,interval是桶的时间间隔。acquire方法用于尝试获取令牌,如果获取成功返回true,否则返回false。
阅读全文