> 文档中心 > springBoot整合rabbitMQ-路由模式-发送消息服务(邮件和钉钉通知)+源码分享gitee仓库免费下载

springBoot整合rabbitMQ-路由模式-发送消息服务(邮件和钉钉通知)+源码分享gitee仓库免费下载

上篇博客介绍了订阅发布模式-也是使用的这个案例。如果对rabbitMQ的订阅发布模式感兴趣可以参考 springboot整合发布订阅模式 文章

目录

  • 简介
  • 实操
    • pom依赖坐标
    • 生产者
    • 消费者
      • 代码
      • 消息消费成功
    • 效果

简介

概念
路由模式是根据具体的key精确的找到具体的队列,投递到指定的队列里。可以根据不同的条件需要。划分多个队列,然后按需投递消息到队列。
队列和交换机的三种创建方式
1,通过rabbitMQ可视化界面配置
2,通过Java配置类
3,通过Java注解
本次以Java配置类为例

实操

pom依赖坐标

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

生产者

代码

配置类

 package com.example.springbootorderrabbitmqproducer.Config;import org.springframework.amqp.core.*;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author 康世行 * @Title: * @Package com.example.springbootorderrabbitmqproducer.Config * @Description: direct交换模式配置类 * @date 2022-01-16 20:02 */@Configurationpublic class DirecRabbittMqConfiguration {    //1:声明注册direc模式的交换机    @Bean    public DirectExchange directExchange(){ return new DirectExchange("direct-exchange",true,false);    }    //2:声明队列    /**      * @Description: 发送短息队列      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-25 19:59      */    @Bean    public Queue smsQueue(){  return new Queue("sms.direct.queue",true);    }    /**      * @Description: 发送邮件消息队列      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-25 20:00      */    @Bean    public Queue emailQueue(){ return new Queue("email.direct.queue",true);    }    //3:完成队列和交换机的绑定关系    /**      * @Description: 发送短息消息队列和Direct交换机进行绑定      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-25 20:02      */    @Bean    public Binding smsBinding(){ return BindingBuilder.bind(smsQueue()).to(directExchange()).with("sms");    }    /**      * @Description: 发送邮件消息队列和Direct交换机进行绑定      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-25 20:03      */    @Bean    public Binding emailBinding(){ return BindingBuilder.bind(emailQueue()).to(directExchange()).with("email");    }}

conroller

 package com.example.springbootorderrabbitmqproducer.controller;import com.example.springbootorderrabbitmqproducer.service.OrderRabbitmqProducerimpl;import io.swagger.annotations.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;/** * @author 康世行 * @Title: * @Package com.example.springbootorderrabbitmqproducer.controller * @Description: 测试日志controller * @date 2021-12-09 8:27 */@RestController@RequestMapping("/send")@Api("测试swagger接口")public class OrderRabbitmqProducerController {    @Autowired    OrderRabbitmqProducerimpl orderRabbitmqProducerimpl;    /**      * @Description: 发送订单,生产者      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-11 20:25      */    @GetMapping("/sendOrder/{DingId}/{content}/{routeKey}")    @ApiOperation("发送订单")    @ApiImplicitParams({     @ApiImplicitParam(name="DingId",value="接收消息的钉钉Id",dataType="String", paramType = "path",required = false),     @ApiImplicitParam(name="content",value="要发送的消息",dataType="String", paramType = "path",required = false),     @ApiImplicitParam(name="routeKey",value="路由key",dataType="String", paramType = "path",required = false)    })    @ApiResponse(code = 400,message = "请求参数没填好")    public String sendOrder(@PathVariable(value = "DingId",required = true) String DingId,@PathVariable(value = "content",required = true)String content,@PathVariable(value = "routeKey",required = true) String routeKey){ //发送订单,消息 String relust= orderRabbitmqProducerimpl.sendOrder(DingId, content,routeKey); return relust;    }}

service

 package com.example.springbootorderrabbitmqproducer.service;import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.HashMap;import java.util.Map;/** * @author 康世行 * @Title: * @Package com.example.springbootorderrabbitmqproducer.service * @Description: 发送订单业务 * @date 2021-12-11 20:27 */@Servicepublic class OrderRabbitmqProducerimpl {    @Autowired    RabbitTemplate rabbitTemplate;    /**      * @Description: 发送订单,生产者      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-11 20:29      */    public String sendOrder(String dingId,String content,String routeKey){ //组装数据 Map<String, String> stringMap=new HashMap<>(); stringMap.put("dingId",dingId); stringMap.put("content",content); //消息投递到队列 //交换机,使用路由模式交换机 String exchangeName="direct-exchange"; //路由key String routingKey=routeKey;rabbitTemplate.convertAndSend(exchangeName,routingKey,stringMap); return "消息投递成功!";    }}

消息投递成功

swagger地址
http://localhost:8089/swagger-ui.html#/order-rabbitmq-producer-controller/sendOrderUsingGET
在这里插入图片描述
投递成功
在这里插入图片描述

可以看到对应的sms队列里多了一条待销费的消息
在这里插入图片描述

消费者

代码

配置类

 package com.example.springbootorderrabbitmqproducer.Config;import org.springframework.amqp.core.*;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author 康世行 * @Title: * @Package com.example.springbootorderrabbitmqproducer.Config * @Description: direct交换模式配置类 * @date 2022-01-16 20:02 */@Configurationpublic class DirecRabbittMqConfiguration {    //1:声明注册direc模式的交换机    @Bean    public DirectExchange directExchange(){ return new DirectExchange("direct-exchange",true,false);    }    //2:声明队列    /**      * @Description: 发送短息队列      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-25 19:59      */    @Bean    public Queue smsQueue(){  return new Queue("sms.direct.queue",true);    }    /**      * @Description: 发送邮件消息队列      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-25 20:00      */    @Bean    public Queue emailQueue(){ return new Queue("email.direct.queue",true);    }    //3:完成队列和交换机的绑定关系    /**      * @Description: 发送短息消息队列和Direct交换机进行绑定      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-25 20:02      */    @Bean    public Binding smsBinding(){ return BindingBuilder.bind(smsQueue()).to(directExchange()).with("sms");    }    /**      * @Description: 发送邮件消息队列和Direct交换机进行绑定      * @param ${tags}      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-25 20:03      */    @Bean    public Binding emailBinding(){ return BindingBuilder.bind(emailQueue()).to(directExchange()).with("email");    }}

消费者–发送钉钉消息

 package com.example.springbootorderrabbitmqconsumer.consumer;import org.springframework.amqp.core.ExchangeTypes;import org.springframework.amqp.rabbit.annotation.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpEntity;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Component;import org.springframework.web.client.RestTemplate;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** * @author 康世行 * @Title: * @Package com.example.springbootorderrabbitmqproducer.consumer * @Description: 订单消费者 * @date 2021-12-11 20:55 */@Component//监听指定队列@RabbitListener(queues = {"sms.direct.queue"})public class OrderRabbimqConsumerDingDing {    @Autowired    RestTemplate restTemplate;    @RabbitHandler    /**      * @Description: 发送钉钉消息      * @param  DingId 钉钉id ,content 要发送的内容      * @return ${return_type}      * @throws      * @author 康世行      * @date 2021-12-11 21:02      */    public void messagerevice(Map<String,String> maps){ //获取队列消息,发送钉钉消息 String dingId = maps.get("dingId"); String content = maps.get("content"); System.out.println("dingId"+dingId); System.out.println("内容"+content); //data体 Map<String, Object> map=new HashMap<>(); List<String> dingIdlist=new ArrayList<>(); dingIdlist.add(dingId); map.put("dingIds",dingIdlist); map.put("groupName","测试"); map.put("messageContent",content); map.put("messageTitle","测试消息队列发送钉钉消息"); map.put("messageUrl","ddd"); map.put("picUrl","ddd"); //htttp请求头,设置请求头信息 HttpHeaders headers=new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/json")); //http请求实体,请求头设置和data存入http请求实体中 HttpEntity parms=new HttpEntity(map, headers);  //发送http请求, 参数1: 接口地址,参数2 请求的数据体(data+headers) 参数3 返回值类型 ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("http://msg.dmsd.tech:8002/dingmessage/send/groupTextMsg", parms, String.class); System.out.println(stringResponseEntity);    }}

消费者–发送email消息

 package com.example.springbootorderrabbitmqconsumer.consumer;import lombok.extern.slf4j.Slf4j;import org.springframework.amqp.core.ExchangeTypes;import org.springframework.amqp.rabbit.annotation.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpEntity;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.stereotype.Component;import org.springframework.web.client.RestTemplate;import java.util.*;/** * @author 康世行 * @Title: * @Package com.example.springbootorderrabbitmqproducer.consumer * @Description: email消费者 * @date 2021-12-12 9:45 */@Component@Slf4j//监听指定队列@RabbitListener(queues = {"email.direct.queue"})public class OrderRabbimqConsumerEmail {    @Autowired    JavaMailSender javaMailSender;    @RabbitHandler    /**       * @Description: 发送email消息       * @param  DingId 钉钉id ,content 要发送的内容       * @return ${return_type}       * @throws       * @author 康世行       * @date 2021-12-11 21:02       */    public void messagerevice(Map<String,String> maps){ //获取队列消息,发送 email消息 String dingId = maps.get("dingId"); String content = maps.get("content"); log.info("dingId"+dingId); log.info("内容"+content); // 设置邮件发送内容 SimpleMailMessage mailMessage = new SimpleMailMessage(); // 发件人: setFrom处必须填写自己的邮箱地址,否则会报553错误 mailMessage.setFrom("1547403415@qq.com"); // 收件人 mailMessage.setTo("18332371417@163.com"); // 抄送收件人:网易邮箱要指定抄送收件人,不然会报 554(发送内容错误) mailMessage.setCc("18332371417@163.com"); // 主题 mailMessage.setSubject("测试rabitMq发送邮费服务"); // 内容 mailMessage.setText(content); try {     javaMailSender.send(mailMessage);     System.out.println("发送简单文本邮件成功,主题是:" + content); } catch (Exception e) {     System.out.println("-----发送简单文本邮件失败!-------" + e.toString());     e.printStackTrace(); }    }}

消息消费成功

在这里插入图片描述
待消费的消息已经被成功消费
在这里插入图片描述

效果

接受的钉钉消息
在这里插入图片描述

接受的邮件
在这里插入图片描述

源码分享-gitee地址
rabbitMQ
在这里插入图片描述
都已经看到这里了,还不给点个赞~ 关注一波,来个一键三连 springBoot整合rabbitMQ-路由模式-发送消息服务(邮件和钉钉通知)+源码分享gitee仓库免费下载