默认缓存案例---模拟手机验证码登录

需求

  • 输入手机号获取验证码,组织文档以短信形式发生给用户(页面模拟)
  • 输入手机号和验证码验证结果

需求分析

  • 提供controller,传入手机号,业务层通过手机号计算出独有的6位验证码数据,存入缓存返回此数据
  • 提供controller,传入手机号和验证码,业务层通过手机号从缓存中读取验证码与输入验证码进行对比,返回对比结果

代码实现
pom:

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

domain:

@Data
public class SMScode {
    private String tele;
    private String code;
}

SMSCodeService:

public interface SMSCodeService {
    public String sendCodeToSMS(String tele);
    public boolean checkCode(SMScode smScode);
}

SMSCodeServiceImpl:

@Service
public class SMSCodeServiceImpl implements SMSCodeService {
    @Autowired
    private CodeUtils codeUtils;

    @Override
//    @Cacheable(value = "SMScode",key = "#tele")
    @CachePut(value = "SMScode",key = "#tele")
    public String sendCodeToSMS(String tele) {
        String code = codeUtils.generator(tele);
        System.out.println(code);
        return code;
    }

    @Override
    public boolean checkCode(SMScode smscode) {
        //取出缓存中的验证码与传递过来的验证码进行比对
        String code = smscode.getCode();
        System.out.println(code);
        String cachecode = codeUtils.get(smscode.getTele());
        System.out.println(cachecode);
        return cachecode.equals(code);
    }
}

CodeUtils:

@Component
public class CodeUtils {

    private String[] patch = {"000000","00000","0000","000","00","0",""};
    public String generator(String tele){

        int hash = tele.hashCode();
        int encryption = 20206666;
        long result = hash ^ encryption;
        long nowTime = System.currentTimeMillis();
        result = result ^ nowTime;
        long code = result % 1000000;
        code= code < 0? -code : code;

        String codeStr = code+"";
        int len = codeStr.length();

        return patch[len]+codeStr;
    }

    //取值
    @Cacheable(value = "SMScode",key = "#tele")
    public String get(String tele) {
        return null;
    }

}

SMSCodeController:

@RestController
@RequestMapping("/sms")
public class SMSCodeController {

    @Autowired
    private SMSCodeService smsCodeService;

    @GetMapping
    public String getCode(String tele){
        String code = smsCodeService.sendCodeToSMS(tele);
        return code;
    }

    @PostMapping
    public boolean checkCode(String tele,String code){
        System.out.println(tele);
        System.out.println(code);
        SMScode smScode = new SMScode();
        smScode.setTele(tele);
        smScode.setCode(code);
        return smsCodeService.checkCode(smScode);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值