public class RedisRateLimiter {
private Jedis jedis;
public RedisRateLimiter(Jedis jedis) {
this.jedis = jedis;
}
public boolean isActionAllowed(String cusKey, int period, int maxCount) {
Response<Long> count = null;
try {
String key = String.format("自定义:%s", cusKey);
long nowTs = System.currentTimeMillis();
Pipeline pipe = jedis.pipelined();
pipe.multi();
pipe.zadd(key, nowTs, "" + nowTs);
pipe.zremrangeByScore(key, 0, nowTs - period * 1000);
count = pipe.zcard(key);
pipe.expire(key, period + 1);
pipe.exec();
pipe.close();
} catch (IOException e) {
e.printStackTrace();
}
return count.get() <= maxCount;
}
public static void main(String[] args) {
Jedis jedis = new Jedis();
RedisRateLimiter limiter = new RedisRateLimiter(jedis);
for (int i = 0; i < 20; i++) {
System.out.println(limiter.isActionAllowed("自定义", 60, 5));
}
}
}
Redis单机限流工具类
最新推荐文章于 2024-05-15 11:03:29 发布