redis限制短信一分钟5条
/**
* 判断一分钟之内,是否可以发送短信:一分钟之内限制5条
* @param phone 手机号
* @return Boolean true-可以发送
*/
@Override
public Boolean sendCount(String phone) {
String key = phone;
//是否可以发送短信
Boolean isSend = true;
//从缓存中获取已发送短信的数量
long size = redisTemplate.opsForList().size(key);
if (size <= 5){
redisTemplate.opsForList().rightPush(key, TimeUtils.timestampNow() + "");
}else {
List<String> time = redisTemplate.opsForList().range(key, 0, size);
Long now = TimeUtils.timestampNow();
//如果最开始的一条距离现在超过1分钟,就移除最左边的,并且添加一条
if (now - Long.valueOf(time.get(0)) > ONE_MINUTE){
redisTemplate.opsForList().leftPop(key);
redisTemplate.opsForList().rightPush(key,TimeUtils.timestampNow() + "");
}else {
//最左边的也在一分钟之内,则不能发送短信
LogUtils.error(LogAction.ERROR,"一分钟之内已发送5条短信,请稍后再试");
isSend = false;
}
}
return isSend;
}