文章目录
前言
短信验证码,手机验证码通常会60秒后可以重新发送,也就意味着缓存后,可以继续覆盖重新缓存。@Cachecache注解在缓存后,将不会再执行,不符合发送验证码的场景。这里需要用到@CachePut,只存不取。
短信验证码的发送和校验
- 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- 编写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);
}
}
- 获取验证码
@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;
}
- 运行服务器,发送请求获取验证码,每次请求,都会获取到新的验证码。拿去获取到的验证比对,进行验证码校验。
总结
上面的demo省略了service层,简化了验证码的发送,正常的情况应该添加service层。
@CachePut和@Cacheable的用法是一样的,区别是CachePut只存不读,会覆盖缓存,而Cacheable既存也读。而短信验证码通常是过了60秒,就需要重新发送,需要覆盖缓存,所以使用@CachePut符合逻辑。
使用@Cacheable获取缓存的数据,所使用的bean需要被springboot托管,否则将不能获取到数据。
@Cacheable(value="smscode",key="#phone")
public String getCode(String phone) {
return null;
}