限流是可以避免外部请求频繁的对系统施压,而且还可以控制用户行为,避免垃圾请求。
下面是利用Redis来控制用户在规定的时间只能请求N次
public boolean isExceedLimit(String userId, String key, int period, int maxCount)
throws IOException {
String newKey = userId + ":" + key;
long nowDate = System.currentTimeMillis();
Pipeline pipeline = jedis.pipelined(); // 创建管道
pipeline.multi();// 开启事务,保证指令的原子操作,不被其它事务打断
pipeline.zadd(newKey, nowDate, nowDate + "");
pipeline.zrangeByScore(newKey, 0, nowDate - period * 1000); // 删除[0, nowDate -period
// * 1000]之前的记录
Response<Long> count = pipeline.zcard(newKey);
pipeline.expire(newKey, period + 1);// 每次设置都能保持key的过期时间
pipeline.exec();// 执行
pipeline.close();
return count.get() <= maxCount;
}
@Test
public void test() {
try {
// 限定1s内操作不得超过3次
for (int i = 0; i < 10; i++) {
System.out.println(isExceedLimit("2333", "test", 1, 3));
}
} catch (IOException e) {
e.printStackTrace();
}
}