https://www.cnblogs.com/dengpengbo/p/10545787.html
https://www.zhulou.net/post/1936.html
参考代码:
/**
* @desc : 校验发送频率
* flagStr: 标识字符串 seconds:每几秒内 count:最多发送几条数据
* @author : 毛会懂
* @create: 2021/9/16 9:45:00
**/
private void checkRateLimitMsg(String flagStr,Integer seconds,Integer count) {
String limitKey = RedisKeyManagement.getKey(RedisKeyManagement.PLAYER_RATE_LIMIT_MSG, Arrays.asList(flagStr));
Long size = redisService.listSize(limitKey);
if (size == 0) {
redisService.expire(limitKey, Constant.ONE_DAY);
}
if (size < count) {
redisService.listAddData(limitKey, new Date());
} else {
Object temp = redisService.listGetData(limitKey, -1);
Date tempDate = (Date) temp;
if (System.currentTimeMillis() - tempDate.getTime() < seconds * 1000) {
log.info("flagStr={},发送频率过高", flagStr);
throw new BusinessException(GameErrorCodeEnum.RATE_LIMIT_MSG);
} else {
redisService.listAddData(limitKey, new Date());
redisService.listTrim(limitKey, 0, count-1);
}
}
}
public Long listSize(String key){
return redisTemplate.opsForList().size(key);
}
public Long listAddData(String key,Object data){
return redisTemplate.opsForList().leftPush(key,data);
}
public Object listGetData(String key,Integer index){
return redisTemplate.opsForList().index(key,index);
}
public Object listRightPop(String key){
return redisTemplate.opsForList().rightPop(key);
}
public void listTrim(String key,Integer index1,Integer index2){
redisTemplate.opsForList().trim(key,index1,index2);
}