java 使用redis 判断同一个手机号一小时内发送短讯是否超过5次

/**
 * 同一个手机号一小时内发送短讯是否超过5次
 * @author yanling.hua
 * @date 2018/8/6 13:37
 */
public Boolean sendCount(String mobile, Short msgType) {
    String key=mobile;
    if(msgType==1){//注册短信
        key = key+"reg";
    }else if(msgType==2){
        key = key+"find";//找回密码短信
    }
    Boolean boo=true;
    long size = redisTemplate.opsForList().size(key);
    if (size <= 5) {
        redisTemplate.opsForList().rightPush(key,System.currentTimeMillis() + "");
    } else {
        List<String> t = redisTemplate.opsForList().range(key, 0, (int) size);
        Long now = System.currentTimeMillis();
        if (now - Long.valueOf(t.get(0)) > 1*60*60*1000) {//最开始的一条距现在超过一小时就移除左边的,并添加一条
            redisTemplate.opsForList().leftPop(key);
            redisTemplate.opsForList().rightPush(key,System.currentTimeMillis() + "");
        } else {//最左的一条也在一小时内,不能发送短信
            boo=false;
        }
    }
    return boo;
}

猜你喜欢

转载自blog.csdn.net/hua_yan_ling/article/details/81482835