使用 StringRedisTemplate 实现发送验证码功能
大体流程:

手机号发送
@Controller
@RequestMapping("/code")
public class SMSCodeApi {
private static final Logger LOG = LoggerFactory.getLogger(SMSCodeApi.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
@GetMapping(path="/send")
@ResponseBody
public Boolean send(@RequestParam("mobile") String mobile) {
if (StringUtils.isEmpty(mobile)) {
LOG.info("手机信号不能为空");
return false;
}
String code = String.valueOf((int)(1000*(Math.random() * 9 + 1)));
Boolean sendResult = sendMobileCode(mobile, code);
if (!sendResult) {
LOG.info("发送验证码失败");
return false;
}
stringRedisTemplate.opsForValue().set(mobile, code);
return true;
}
private boolean sendMobileCode(String mobile, String code) {
LOG.info("");
return true;
}
}
接下来使用 mail 来发送验证码
先参考 spring boot 集成 mail,30秒看完
@Controller
@RequestMapping("/email")
public class EmailCodeApi {
private static final Logger LOG = LoggerFactory.getLogger(EmailCodeApi);
@Autowired
private JavaMailSender mailSender;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Value("${sendEmailAddress}")
private String sendEmailAddress;
@GetMapping("/send")
@ResponseBody
public SimpleMailMessage sendMail(@RequestParam String email) {
if (StringUtils.isEmpty(email)) {
LOG.info("邮箱不能为空");
return null;
}
SimpleMailMessage message = new SimpleMailMessage();
if (StringUtils.isEmpty(sendEmailAddress)) {
LOG.info("发件人不能为空");
return null;
}
String code = String.valueOf((int)(1000 * (Math.random() * 9 + 1)));
message.setFrom(sendEmailAddress);
message.setTo(email);
message.setSubject("发送验证码");
message.setText(code);
mailSender(message);
stringRedisTemplate.opsForValue().set(email, code);
return message;
}
}
校验验证码的流程
大体流程

@GetMapping
@ResponseBody
public Boolean verificateCode(@RequestParam String email, @RequestParam String code) {
if (StringUtils.isEmpty(email)) {
LOG.info("邮箱不能为空");
return false;
}
if (StringUtils.isEmpty(code)) {
LOG.info("验证码不能为空");
return false;
}
String existCode = stringRedisTemplate.opsForValue().get(email);
if (!code.equals(existCode)) {
LOG.info("手机验证码失败");
return false;
}
return true;
}