应用场景
- 需要限制某个用户的行为
- 接口调用过于频繁
实现的几种方式
1、
代码示例
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
public class SimpleRateLimiter {
private Jedis jedis;
public SimpleRateLimiter(Jedis jedis) {
this.jedis = jedis;
}
public boolean isActionAllowed(String userId, String actionKey, int period, int maxCount){
String key = String.format("hist:%s:%s", userId, actionKey);
long nowTs = System.currentTimeMillis();
Pipeline pipe = jedis.pipelined();
pipe.multi();
pipe.zadd(key,nowTs,""+nowTs);
pipe.zremrangeByRank(key,0,nowTs-period*10);
Response<Long> count=pipe.zcard(key);
pipe.expire(key,period+1);
pipe.exec();
pipe.close();
return count.get()<=maxCount;
}
public static void main(String[] args) {
Jedis jedis=new Jedis();
SimpleRateLimiter limiter=new SimpleRateLimiter(jedis);
for(int i=0;i<20;i++){
System.out.println(limiter.isActionAllowed("laoqian","reply",60,5));
}
}
}