springboot基础(38):短信验证码缓存案例@CachePut

本文介绍了如何在Spring Boot中利用缓存管理实现短信验证码的发送和校验。通过@CachePut和@Cacheable注解,确保每次请求都能获取到新的验证码,并在60秒后允许重新发送。示例代码展示了发送验证码的Controller和Util类,以及验证码实体类的定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

短信验证码,手机验证码通常会60秒后可以重新发送,也就意味着缓存后,可以继续覆盖重新缓存。@Cachecache注解在缓存后,将不会再执行,不符合发送验证码的场景。这里需要用到@CachePut,只存不取。

短信验证码的发送和校验

  1. 导入依赖
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

  1. 编写controller
@RestController
@RequestMapping("/sms")
public class SmsCodeController {

    @Autowired
    private SmsUtils smsUtils;

    @GetMapping
    public String getCode(String phone) {
        return smsUtils.createCode(phone);
    }

    @PostMapping
    public boolean checkCode(SmsCode smsCode) {
        String code = smsCode.getCode();
        String code2 = smsUtils.getCode(smsCode.getPhone());
        return code.equals(code2);
    }

}
  1. 获取验证码
@Component
public class SmsUtils {

    @CachePut(value="smscode",key="#phone")
    public String createCode(String phone) {
        int rand = new Random().nextInt(1000_000);
        return String.format("%06d",rand);
    }


    @Cacheable(value="smscode",key="#phone")
    public String getCode(String phone) {
        return null;
    }

}

实体类

import lombok.Data;

@Data
public class SmsCode {

    private String phone;
    private  String code;
}

  1. 运行服务器,发送请求获取验证码,每次请求,都会获取到新的验证码。拿去获取到的验证比对,进行验证码校验。
    在这里插入图片描述
    在这里插入图片描述

总结

上面的demo省略了service层,简化了验证码的发送,正常的情况应该添加service层。
@CachePut和@Cacheable的用法是一样的,区别是CachePut只存不读,会覆盖缓存,而Cacheable既存也读。而短信验证码通常是过了60秒,就需要重新发送,需要覆盖缓存,所以使用@CachePut符合逻辑。
使用@Cacheable获取缓存的数据,所使用的bean需要被springboot托管,否则将不能获取到数据。

   @Cacheable(value="smscode",key="#phone")
    public String getCode(String phone) {
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值