手机验证码缓存

package cn.miloer.museumsystemservice.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Objects;
import java.util.Random;

/**
 * @author milo
 * @create 2023/4/13 10:54
 * 手机验证码缓存
 */
@Slf4j
@Component
public class SMSRedisTemplate {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void set(String phone,String code){
        code=code+"_"+System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set("mu_cache:sms_"+phone,code, Duration.ofMinutes(5));
    }
    public boolean checkCode(String phone,String code){
        String tempCode=stringRedisTemplate.opsForValue().get("mu_cache:sms_"+phone);
        if(StringUtils.isNotBlank(code)&&tempCode!=null){
            tempCode=tempCode.split("_")[0];
            if(Objects.equals(code.toLowerCase(),tempCode.toLowerCase())){
                stringRedisTemplate.delete("mu_cache:sms_"+phone);
                return true;
            }
        }
        return false;
    }
    public boolean isLimitTime(String phone){
        String tempCode=stringRedisTemplate.opsForValue().get("mu_cache:sms_"+phone);
        if(StringUtils.isNotBlank(tempCode)) {
            long l = Long.parseLong(tempCode.split("_")[1]);
            // 当前系统事件减去之前验证码存入的事件 小于60000毫秒=60秒
            if (System.currentTimeMillis() -l < 60000) {
                return true;
            }
        }
        return false;
    }
    public String getCode(){
        Random rand = new Random();
        String result="";
        for (int i = 0; i < 6; i++) {
            result+=rand.nextInt(10);
        }
        return result;
    }
}
 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值