消息队列的配置类
消息发送的详细步骤
复制配置类,接受方
在接收方,接受控制层发送的map
import com.offcn.utils.SMSUtils;
import org.apache.http.HttpResponse;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class ResiverListener {
@Autowired
private SMSUtils smsUtils;
//注解中标明获取的是哪个队列的消息
@RabbitListener(queues = "spring.queue")
public void resiverMessage(Map<String,String> map){
String phone = map.get("phone");
String code = map.get("code");
//发送短信
smsUtils.sendCode(phone, code);
}
}
然后在接收方注入短信验证的工具类的对象
短信验证的详细步骤
然后调用工具类中发验证码的方法,传递进去号码和验证码
控制层
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.utils.SMSUtils;
import org.apache.http.HttpResponse;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("sms")
public class SMSController {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private SMSUtils smsUtils;
@RequestMapping("sendCode/{phone}/{code}")
public Result sendCode(@PathVariableString phone,@PathVariable String code){
//创建一个map用于存放电话号码,验证码等
Map<String,String> map = new HashMap<>();
map.put("phone",phone);
map.put("code", code);
//发送消息,放队列名和发送的数据
rabbitTemplate.convertAndSend("spring.queue",map);
return new Result(true, StatusCode.OK,"success");
}
}
然后项目中验证可以生成后,存放进redis,然后手机号作为键,验证码作为值,进行验证
//1. 生成验证码
String code = UUID.randomUUID().toString().substring(0,4);
//2. 发送验证码
Map<String,String> map = new HashMap<>();
map.put("phone", phone);
map.put("code", code);
rabbitTemplate.convertAndSend("spring.queue", map);
//将验证码存入redis
redisTemplate.boundHashOps("smscode").put(phone, code);