[JAVA] Springboot整合RabbitMQ实现通过RabbitMQ进行项目的连接

2375 0
王子 2022-11-8 17:26:05 | 显示全部楼层 |阅读模式
目录

    什么是RabbitMQ消息队列:接受并转发消息,类似于快递公司
      消息队列的优点消息队列的特性
    RabbitMQ特点RabbitMQ核心概念
      Producer :消息生产者Message :消息Exchange :交换机Binding :绑定交换机和队列Routing key :路由键,决定路由规则Queue :队列,存储消息Connection :连接服务端Channel :信道,读写数据.Consumer :消费者Broker :服务实例Virtual host :虚拟主机,用于区分不同服务,类似于不同域名,不会相互影响
    安装RabbitMQ
      LINUX环境下安装3.8.2 使用Xshell常用命令Windows
    RabbitMQ实操分布了解
      1 生产者2 消费者
    Springboot 整合RabbitMQ代码实操
      生产者消费者运行结果



什么是RabbitMQ

一款基于AMQP用于软件之间通信的中间件 。消费并不需要确保提供方存在,实现了服务之间的高度解耦
AMQP,即Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计。消息中间件主要用于组件之间的解耦,消息的发送者无需知道消息使用者的存在,反之亦然。AMQP的主要特征是面向消息、队列、路由(包括点对点和发布/订阅)、可靠性、安全。
RabbitMQ是一个开源的AMQP实现,服务器端用Erlang语言编写,支持多种客户端,如:Python、Ruby、.NET、Java、JMS、C、PHP、ActionScript、XMPP、STOMP等,支持AJAX。用于在分布式系统中存储转发消息,在易用性、扩展性、高可用性等方面表现不俗。
基本组成:Queue:消息队列,存储消息的队列,消息到达队列并转发给指定的消费方;
Exchange消息队列交换机,按一定的规则将消息路由转发到某个队列,对消息进行过虑;
消费者:消费信息;
提供者:发送消息;
官网 Messaging that just works — RabbitMQ





消息队列:接受并转发消息,类似于快递公司

product : 消息的发送者,生产者
consumer:消息的消费者,从队列获取消息,并且使用
queue :先进先出,一个queue可以对应多个consumer

消息队列的优点

代码解耦,提高系统稳定性
应对流量高峰,降低流量冲击,面对秒杀这种情况时,请求进来先去排队,可以保证系统的稳定
异步执行,提高系统响应速度

消息队列的特性

性能好
它是一种基础组件
支持消息确认,为了防止数据丢失以及应对特殊情况,在数据没有处理完,没有确认之前消息不会丢掉。

RabbitMQ特点

路由能力灵活强大
开源免费
支持编程语言多
应用广泛,社区活跃
有开箱即用的监控和管理后台

RabbitMQ核心概念



生产者数量是不限制的,生产者生产的消息Message进入交换机,交换一可以连接多个队列也可以仅连接一个对联,交换机与队列的关系是不固定的,交换机会绑定到队列上(Binding)根据的规则就是Routing Key路由键用来确定交换机与队列如何进行绑定 ,消息经过交换机经过连接发送个消费者,在连接中多多个信道,数据都是在信道中进行读写的,消费者从中提取想要的消息进行处理。Broker(服务实例)也就是服务端,Virtual Host (虚拟主机)同一个RabbitMQ可能给多个服务进行使用,服务与服务之间想要隔离开就可以使用虚拟主机进行隔离。

Producer :消息生产者


Message :消息


Exchange :交换机


Binding :绑定交换机和队列


Routing key :路由键,决定路由规则


Queue :队列,存储消息


Connection :连接服务端


Channel :信道,读写数据.


Consumer :消费者


Broker :服务实例


Virtual host :虚拟主机,用于区分不同服务,类似于不同域名,不会相互影响


安装RabbitMQ


LINUX环境下安装3.8.2 使用Xshell

先进行环境配置
连接成功以后输入
echo "export LC_ALL=en_US.UTF-8" >> /etc/profile 把编码设置成utf-8
source /etc/profile 使设置生效
输入curl -s https://packagecloud.io/install/repositories/rabbitmq/rabbitmq-server/script.rpm.sh | sudo bash 配置RabbitMQ源


看到这个命令就可以进行下一步了
curl -s https://packagecloud.io/install/repositories/rabbitmq/erlang/script.rpm.sh | sudo bash
配置erlang环境


看到这个命令进行下一步
sudo yum install rabbitmq-server-3.8.2-1.el7.noarch


输入y



常用命令

开启web管理界面
rabbitmq-plugins enable rabbitmq_management
停止RabbitMQ
rabbitmqctl stop
设置开机启动
systemctl enable rabbitmq-server
启动RabbitMQ
systemctl start rabbitmq-server
看看端口有没有起来,查看状态
rabbitmqctl status
要检查RabbitMQ服务器的状态,请运行:
systemctl status rabbitmq-server

Windows

先安装erlang并配置环境,安装RabbitMQ
链接:https://pan.baidu.com/s/1S4D2zh-NSoXh-QPQVNBi-w
提取码:1111
这里直接放上链接,erlang安装好后要去配置环境


解压缩后sbin目录下,rabbitmq-server.bat 这个文件就是启动
用终端cmd输入:
cd d:\你的RabbitMQ按照地址\sbin
rabbitmq-plugins enable rabbitmq_management
rabbitmq-server
然后就可以用guest访问http://127.0.0.1:15672/#/
账号密码都是guest



RabbitMQ实操分布了解


1 生产者

这里的前提是你有个云服务器,并且已经完成了配置,为了操作简便这里就用本机了哈
我们要有一个管理者啊在sbin目录输入
rabbitmqctl add_user newadmin newpassword
rabbitmqctl set_user_tags newadmin administrator
rabbitmqctl set_permissions -p / newadmin ".*" ".*" ".*"//这一步已经把在虚拟主机上把权限配置了
账号test 密码123456
新建一个mavene项目,


2 引入依赖
  1. <dependencies>
  2.         <dependency>
  3.             <groupId>com.rabbitmq</groupId>
  4.             <artifactId>amqp-client</artifactId>
  5.             <version>5.8.0</version>
  6.         </dependency>
  7. <!--        记录日志-->
  8.         <dependency>
  9.             <groupId>org.slf4j</groupId>
  10.             <artifactId>slf4j-nop</artifactId>
  11.             <version>1.7.29</version>
  12.         </dependency>
  13.     </dependencies>
复制代码
  1. /**
  2. * 描述 发送类 连接到服务端 发送 退出
  3. */
  4. public class Send {
  5.     //设置队列的名字
  6.     private final static String QUEUE_NAME = "hello";
  7.     public static void main(String[] args) throws IOException, TimeoutException {
  8.         //创建连接工厂
  9.         ConnectionFactory factory = new ConnectionFactory();
  10.         //设置RabbitMQ地址
  11.         factory.setHost("127.0.0.1");
  12.         factory.setUsername("test");
  13.         factory.setPassword("123456");
  14.         //建立连接
  15.         Connection connection = factory.newConnection();
  16.         //获得信道
  17.         Channel channel = connection.createChannel();
  18.         //声明队列
  19.         //                   queueName    持久存在?  独有?       自动删除?
  20.         channel.queueDeclare(QUEUE_NAME, false, false, false, null);
  21.         //发布消息
  22.         String message = "Hello World! ";
  23.         channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
  24.         System.out.println("发送了消息:" + message);
  25.         //关闭连接
  26.         channel.close();
  27.         connection.close();
  28.     }
  29. }
复制代码
运行一下


发送成功了 如果我么连接不到RabbitMQ是无法正常发送的

2 消费者

我么要做的就是把刚刚发送的存储在队列里的消息拿到并打印出来
  1. **
  2. * 描述:     接收消息,并打印,持续运行
  3. */
  4. public class Recvice {
  5.     private final static String QUEUE_NAME = "hello";
  6.     public static void main(String[] args) throws IOException, TimeoutException {
  7.         //创建连接工厂
  8.         ConnectionFactory factory = new ConnectionFactory();
  9.         //设置RabbitMQ地址
  10.         factory.setHost("127.0.0.1");
  11.         factory.setUsername("test");
  12.         factory.setPassword("123456");
  13.         //建立连接
  14.         Connection connection = factory.newConnection();
  15.         //获得信道
  16.         Channel channel = connection.createChannel();
  17.         //声明队列
  18.         channel.queueDeclare(QUEUE_NAME, false, false, false, null);
  19.         //接收消息并消费       queueName    自动签收   处理消息
  20.         channel.basicConsume(QUEUE_NAME, true, new DefaultConsumer(channel){
  21.             @Override
  22.             public void handleDelivery(String consumerTag, Envelope envelope,
  23.                     BasicProperties properties, byte[] body) throws IOException {
  24.                 String message = new String(body, "UTF-8");
  25.                 System.out.println("收到消息:" + message);
  26.             }
  27.         });
  28.     }
  29. }
复制代码


可以看到Receive是(打错了,尬)一直运行的,我么把发送的消息改一下再发送试试




我们之前设置的是自动接收消息们可以看到运行时成功的


去web控制台也能看到是有hello这个队列的 还有更多的功能就靠你们自己去探索了

Springboot 整合RabbitMQ代码实操

1 新建两个Spring项目 一个生产者,一个消费者不需要引入依赖一会儿手动加




主要关键是定义队列 queue 定义routingKey

生产者

配置文件
guest是默认的用户只能本机时使用
  1. server.port=8080
  2. spring.application.name=producer
  3. spring.rabbitmq.addresses=127.0.0.1:5672
  4. spring.rabbitmq.username=guest
  5. spring.rabbitmq.password=guest
  6. spring.rabbitmq.virtual-host=/
  7. spring.rabbitmq.connection-timeout=15000
复制代码
依赖
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.     <modelVersion>4.0.0</modelVersion>
  5.     <parent>
  6.         <groupId>org.springframework.boot</groupId>
  7.         <artifactId>spring-boot-starter-parent</artifactId>
  8.         <version>2.2.1.RELEASE</version>
  9.         <relativePath/> <!-- lookup parent from repository -->
  10.     </parent>
  11.     <groupId>com.example</groupId>
  12.     <artifactId>spring-boot-rabbirmq-producer</artifactId>
  13.     <version>0.0.1-SNAPSHOT</version>
  14.     <name>spring-boot-rabbirmq-producer</name>
  15.     <description>spring-boot-rabbirmq-producer</description>
  16.     <properties>
  17.         <java.version>1.8</java.version>
  18.     </properties>
  19.     <dependencies>
  20.         <dependency>
  21.             <groupId>org.springframework.boot</groupId>
  22.             <artifactId>spring-boot-starter</artifactId>
  23.         </dependency>
  24.         <dependency>
  25.             <groupId>org.springframework.boot</groupId>
  26.             <artifactId>spring-boot-starter-amqp</artifactId>
  27.         </dependency>
  28.         <dependency>
  29.             <groupId>org.springframework.boot</groupId>
  30.             <artifactId>spring-boot-starter-test</artifactId>
  31.             <scope>test</scope>
  32.             <exclusions>
  33.                 <exclusion>
  34.                     <groupId>org.junit.vintage</groupId>
  35.                     <artifactId>junit-vintage-engine</artifactId>
  36.                 </exclusion>
  37.             </exclusions>
  38.         </dependency>
  39.     </dependencies>
  40.     <build>
  41.         <plugins>
  42.             <plugin>
  43.                 <groupId>org.springframework.boot</groupId>
  44.                 <artifactId>spring-boot-maven-plugin</artifactId>
  45.             </plugin>
  46.         </plugins>
  47.     </build>
  48. </project>
复制代码
我们只在原基础上加了一个依赖
  1. spring-boot-starter-amqp
复制代码
启动类
  1. @SpringBootApplication
  2. public class SpringBootRabbirmqProducerApplication {
  3.     public static void main(String[] args) {
  4.         SpringApplication.run(SpringBootRabbirmqProducerApplication.class, args);
  5.     }
  6. }
复制代码
发送消息类
  1. /**
  2. * 描述:     发送消息
  3. */
  4. @Component
  5. public class MessageSender {
  6.     @Autowired
  7.     private AmqpTemplate rabbitmqTemplate;
  8.     public void send1() {
  9.         String message = "This is message 1, routing key is hello.sayHello";
  10.         System.out.println("发送了:"+message);
  11.         //                                      交换机         key             内容
  12.         this.rabbitmqTemplate.convertAndSend("bootExchange", "hello.sayHello", message);
  13.     }
  14.     public void send2() {
  15.         String message = "This is message 2, routing key is hello.sayNothing";
  16.         System.out.println("发送了:"+message);
  17.         this.rabbitmqTemplate.convertAndSend("bootExchange", "hello.sayNothing", message);
  18.     }
  19. }
复制代码
配置类
  1. /**
  2. * 描述:     rabbitmq配置类
  3. */
  4. @Configuration
  5. public class TopicRabbitConfig {
  6.     //定义队列 注意类型:import org.springframework.amqp.core.Queue;
  7.     @Bean
  8.     public Queue queue1() {
  9.         return new Queue("queue1");
  10.     }
  11.     @Bean
  12.     public Queue queue2() {
  13.         return new Queue("queue2");
  14.     }
  15.     //交换机
  16.     @Bean
  17.     TopicExchange exchange() {
  18.         return new TopicExchange("bootExchange");
  19.     }
  20.     //将队列绑定到交换机
  21.     @Bean
  22.     Binding bingdingExchangeMessage1(Queue queue1, TopicExchange exchange) {
  23.         return BindingBuilder.bind(queue1).to(exchange).with("hello.sayHello");
  24.     }
  25.     @Bean
  26.     Binding bingdingExchangeMessage2(Queue queue2, TopicExchange exchange) {
  27.         return BindingBuilder.bind(queue2).to(exchange).with("hello.#");
  28.     }
  29. }
复制代码
这里注意第一个消息的routingkey是跟配置类一样的hello.sayHello 就代表 我们这个交换机是仅能识别hello.sayHello的
第二个交换机的routingkey是hello.# 那就意味着只要key是hello.()类型我们都能识别到也就是第一个和第二个消息都能识别到
编写测试类用来发送消息
  1. @SpringBootTest
  2. class SpringBootRabbirmqProducerApplicationTests {
  3.     @Autowired
  4.     MessageSender messageSender;
  5.     @Test
  6.     public void send1(){
  7.         messageSender.send1();
  8.     }
  9.     @Test
  10.     public void send2(){
  11.         messageSender.send2();
  12.     }
  13. }
复制代码
生产者就编写完成

消费者

配置文件,大体一样,用户我用的管理者权限的用户test 端口号不能一样
  1. server.port=8081
  2. spring.application.name=consumer
  3. spring.rabbitmq.addresses=127.0.0.1:5672
  4. spring.rabbitmq.username=test
  5. spring.rabbitmq.password=123456
  6. spring.rabbitmq.virtual-host=/
  7. spring.rabbitmq.connection-timeout=15000
复制代码
依赖 与生产者一样只用加一个
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.     <modelVersion>4.0.0</modelVersion>
  5.     <parent>
  6.         <groupId>org.springframework.boot</groupId>
  7.         <artifactId>spring-boot-starter-parent</artifactId>
  8.         <version>2.2.1.RELEASE</version>
  9.         <relativePath/> <!-- lookup parent from repository -->
  10.     </parent>
  11.     <groupId>com.example</groupId>
  12.     <artifactId>spring-boot-rabbitmq-consumer</artifactId>
  13.     <version>0.0.1-SNAPSHOT</version>
  14.     <name>spring-boot-rabbitmq-consumer</name>
  15.     <description>spring-boot-rabbitmq-consumer</description>
  16.     <properties>
  17.         <java.version>1.8</java.version>
  18.     </properties>
  19.     <dependencies>
  20.         <dependency>
  21.             <groupId>org.springframework.boot</groupId>
  22.             <artifactId>spring-boot-starter</artifactId>
  23.         </dependency>
  24.         <dependency>
  25.             <groupId>org.springframework.boot</groupId>
  26.             <artifactId>spring-boot-starter-test</artifactId>
  27.             <scope>test</scope>
  28.             <exclusions>
  29.                 <exclusion>
  30.                     <groupId>org.junit.vintage</groupId>
  31.                     <artifactId>junit-vintage-engine</artifactId>
  32.                 </exclusion>
  33.             </exclusions>
  34.         </dependency>
  35.         <dependency>
  36.             <groupId>org.springframework.boot</groupId>
  37.             <artifactId>spring-boot-starter-amqp</artifactId>
  38.         </dependency>
  39.     </dependencies>
  40.     <build>
  41.         <plugins>
  42.             <plugin>
  43.                 <groupId>org.springframework.boot</groupId>
  44.                 <artifactId>spring-boot-maven-plugin</artifactId>
  45.             </plugin>
  46.         </plugins>
  47.     </build>
  48. </project>
复制代码
启动类
  1. @SpringBootApplication
  2. public class SpringBootRabbitmqConsumerApplication {
  3.     public static void main(String[] args) {
  4.         SpringApplication.run(SpringBootRabbitmqConsumerApplication.class, args);
  5.     }
  6. }
复制代码
消费者1 消费者一绑的队列是queue1 接收消息是要通过交换机-> 队列-> 信道 那就意味着队列1中将有hello.sayHello
  1. /**
  2. * 描述:     消费者1
  3. */
  4. @Component
  5. @RabbitListener(queues = "queue1")
  6. public class Receiver1 {
  7.     //处理方法
  8.     @RabbitHandler
  9.     public void process(String message) {
  10.         System.out.println("Receiver1: " + message);
  11.     }
  12. }
复制代码
消费者2
  1. /**
  2. * 描述:     消费者2
  3. */
  4. @Component
  5. @RabbitListener(queues = "queue2")
  6. public class Receiver2 {
  7.     @RabbitHandler
  8.     public void process(String message) {
  9.         System.out.println("Receiver2: " + message);
  10.     }
  11. }
复制代码
运行结果



这本身是两个独立的项目,但是通过RabbitMQ使两个项目产生了连接,Springboot完成了对RabbitMQ的整合。
到此这篇关于Springboot整合RabbitMQ实现通过RabbitMQ进行项目的连接的文章就介绍到这了,更多相关Springboot整合RabbitMQ内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行