Java利用Redis zset判断最近一段时间的调用次数
public boolean fuck(Bo bo) {
//maxFrequencyInterval为需要统计频率的时间间隔
if (maxFrequencyInterval >= 0) {
String frequencyKey = getFrequencyKey(bo);
long now = System.currentTimeMillis();
//删除zset中过时的元素
stringRedisTemplate.opsForZSet().removeRangeByScore(frequencyKey, 0, now - 1000d * maxFrequencyInterval);
Long frequency = stringRedisTemplate.opsForZSet().zCard(frequencyKey);
//maxFrequency为这段时间间隔内能接受的最大调用次数
if (frequency != null && frequency >= maxFrequency) {
return false;
}
//key无所谓 分数是当前时间戳 用作删除条件
stringRedisTemplate.opsForZSet().add(frequencyKey, StringUtil.EMPTY_STRING, now);
if (frequency != null && frequency == 0) {
//创建zset时设置过期时间
stringRedisTemplate.expire(frequencyKey, maxFrequencyInterval * 10L, TimeUnit.SECONDS);
}
}
return true;
}