1。Controller层用户请求发送验证码
调用service层的方法,并直接返回true,其他的交给消息队列处理
@RequestMapping("/send_verify")
@ResponseBody
public Map<String, Object> sendVerify(String phone) {
Map<String, Object> result = new HashMap<>();
System.out.println("进入send");
//将手机号存入消息队列
loginService.sendPhoneNum(phone);
result.put("success", true);
return result;
}
2.Service层sendPhoneNum方法
将手机号发送至某一主题
//生产者发送手机号
@Override
public void sendPhoneNum(String phone) {
kafkaTemplate.send("phone-topic",phone);
}
3.Service层监听并处理方法
消费者取手机号,
生成四位随机数,
调用RedisDao方法存验证码,手机号作为key
并发送短信
@Override
@KafkaListener(topics = "phone-topic")
public void sendVerifyCode(String phone) {
Random random = new Random();
//生成四位随机数
Integer num = random.nextInt(10000);
String code = String.format("%04d", num);
//存入redis
redisDao.strSet(phone, code, 300);
//发送验证码
System.out.println("向手机"+phone+"发送验证码");
try {
Thread.sleep(10000); //休眠10秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发送完毕");
}
4.RedisDao 存取 验证码
@Override
public void strSet(String key, String value, Integer seconds) {
redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
}
@Override
public String strGet(String key) {
return redisTemplate.opsForValue().get(key);
}
5.Controller用户使用验证码请求登录
通过手机号进行redis取出数据,并判断做出回应
如果是null证明没有验证码(验证码超时)
如果不等于证明不一致(验证码)
如果等于(登陆成功)
@RequestMapping("/phone_login")
@ResponseBody
public Map<String, Object> phoneLogin(String phone, String number) {
Map<String, Object> result = new HashMap<>();
String code = loginService.getVerifyCode(phone);
if (code == null) {
result.put("success", false);
result.put("message", "验证码超时");
}
else if (!code.equals(number)) {
result.put("success", false);
result.put("message", "验证码错误");
}
else {
result.put("success", true);
}
return result;
}
版权声明:本文为zhhhhhh1213原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。