java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > RabbitMQ在springboot实现短信服务的异步通信

RabbitMQ在springboot中实现短信服务的异步通信方式

作者:胡思乱想罢了~

RabbitMQ是一个开源消息中间件,适用于异步通信、应用解耦、可靠消息传递、灵活路由、延迟消息处理和分布式系统调等场景,SpringBoot使用需要新建队列、交换机并配置绑定,文章通过短信验证码服务为例,演示了RabbitMQ在项目中的应用场景和配置方法

springboot中RabbitMQ基本使用

RabbitMQ是一个开源的消息中间件

具有以下用途和优点:

RabbitMQ是一个功能强大、可靠性高且易于使用的消息中间件。它在异步通信、应用解耦、可靠消息传递、灵活的消息路由和交换、延迟消息处理以及分布式系统中的协调等方面具有广泛应用。

在SpringbBoot在使用首先需要在rabbitmq管理界面新建队列和交换机。

RabbitMQ支持多种类型的交换机,用于定义消息的路由规则。

以下是几种常见的交换机类型:

不同类型的交换机适用于不同的应用场景,开发者可以根据具体需求选择适合的交换机类型来进行消息路由和分发。

在项目中引入依赖

<!-- RabbitMQ -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

yml文件配置

rabbitmq的用户名和密码都为默认

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/market?useSSl=true&useUnicode=true$characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: root
    password: 010409
  rabbitmq:
      host: 127.0.0.1
      port: 5672
      username: guest
      password: guest

交换机与队列绑定配置

@Configuration
public class RabbitMQConfig {
    private static final String MARKET = "market";
    private static final String ORDER = "order";
    private static final String EXCHANGE = "market.exChanges";
    @Bean
    public Queue queue01(){
        return new Queue(MARKET);
    }
    @Bean
    public Queue queue02(){
        return new Queue(ORDER);
    }
    @Bean
    public DirectExchange fanoutExchange(){
        return new DirectExchange(EXCHANGE);
    }
    // 绑定交换机和队列
    @Bean
    public Binding binding01(){
        return BindingBuilder.bind(queue01()).to(fanoutExchange()).with("market");
    }
    @Bean
    public Binding binding02(){
        return BindingBuilder.bind(queue02()).to(fanoutExchange()).with("order");
    }
}

应用场景

短信验证码服务,这里我使用的是阿里云短信服务SMS,将短信验证码与前端输入的手机号存入队列中,将验证码存入redis中,方便后续注册时验证码验证,最后监听队列拿到信息后发送短信。

SMS依赖与配置,需要将配置修改为自己的

<!--  阿里云短信依赖  -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.5.16</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>2.1.0</version>
</dependency>
@Service
public class SmsService {
    public boolean send(Map<String, Object> param, String phone) {

        if(StringUtils.isEmpty(phone)) return false;
        //default 地域节点,默认就好  后面是 阿里云的 id和秘钥(这里记得去阿里云复制自己的id和秘钥哦)
        DefaultProfile profile = DefaultProfile.getProfile("default",  "LTAI5tNtEzgs7etoRVhWQuXz", "X8odaVou1eSwT0boKEgvYxPSUtWafL");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();

        request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("PhoneNumbers", phone);  //手机号
        request.putQueryParameter("SignName", "阿里云短信测试");    //申请阿里云 签名名称(暂时用阿里云测试的,自己还不能注册签名)
        request.putQueryParameter("TemplateCode",  "SMS_154950909"); //申请阿里云 模板code(用的也是阿里云测试的)
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

发送短信的接口:

@RequestMapping("/sendCode")
public Result sendCode(String phone){
    return UserService.sendCode(phone);
}

实现:

   @Override
    public Result sendCode(String phone) {
        // 1.校验手机号
        String regex = "^1[3456789]\\d{9}$";

        if (!phone.matches(regex)) {
            // 2.如果不符合,返回错误信息
            return new Result(100,"手机号格式错误!");
        }

//      3. 生成验证码
        String code = "";
        for (int i = 0; i < 6; i++) {
            int var = new Random().nextInt(10);
            code = code + var;
        }

        Map<String,Object> param = new HashMap<>();
        param.put("code", code);

        // 4.保存验证码到 redis
        redisCache.setCacheObject(phone,code);

        Map<String,String> map=new HashMap();
        map.put("phone", phone);
        map.put("code", code);
        // 5.保存验证码和手机号到队列
        rabbitTemplate.convertAndSend("market.exChanges","market",map);

        return new Result(200, "发送成功");
    }

监听队列并发送短信。

@RabbitListener(queues = "market")
@RabbitHandler
public void executeSPC(Map<String, String> map, Channel channel, @Headers Map<String, Object> headers) throws IOException {
    try {
        Map<String,Object> param = new HashMap<>();
        param.put("code", map.get("code"));
        smsService.send(param, map.get("phone"));

        // 手动发送ACK,确认消息已接收
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);
    } catch (Exception e) {
        // 处理异常情况,根据业务需要选择是否重新入列或者拒绝消息等操作
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicNack(deliveryTag, false, true);
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文