消息队列+短信验证

消息队列的配置类
消息发送的详细步骤
复制配置类,接受方

在接收方,接受控制层发送的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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值