RabbitMQ 基础

1.初识RabbitMQ

1.1.同步调用

我们现在基于OpenFeign的调用都属于是同步调用,那么这种方式存在哪些问题呢?

  • 拓展性差
  • 性能下降
  • 级联失败

而要解决这些问题,我们就必须用异步调用的方式来代替同步调用

1.2.异步调用

异步调用方式其实就是基于消息通知的方式,一般包含三个角色:

  • 消息发送者:投递消息的人,就是原来的调用方
  • 消息Broker:管理、暂存、转发消息,你可以把它理解成微信服务器
  • 消息接收者:接收和处理消息的人,就是原来的服务提供方

在异步调用中,发送者不再直接同步调用接收者的业务接口,而是发送一条消息投递给消息Broker。然后接收者根据自己的需求从消息Broker那里订阅消息。每当发送方发送消息后,接受者都能获取消息并处理。这样,发送消息的人和接收消息的人就完全解耦了。

异步调用的优势包括:

  • 耦合度更低
  • 性能更好
  • 业务拓展性强
  • 故障隔离,避免级联失败

当然,异步通信也并非完美无缺,它存在下列缺点:

  • 完全依赖于Broker的可靠性、安全性和性能
  • 架构复杂,后期维护和调试麻烦

2.RabbitMQ

RabbitMQ是基于Erlang语言开发的开源消息通信中间件,官网地址:
Messaging that just works — RabbitMQ

2.1.安装

我们同样基于Docker来安装RabbitMQ,使用下面的命令即可:

docker run \
 -e RABBITMQ_DEFAULT_USER=liming \
 -e RABBITMQ_DEFAULT_PASS=123321 \
 -v mq-plugins:/plugins \
 --name mq \
 --hostname mq \
 -p 15672:15672 \
 -p 5672:5672 \
 --network liming \
 -d \
 rabbitmq:3.8-management

在这里插入图片描述

可以看到在安装命令中有两个映射的端口:

  • 15672:RabbitMQ提供的管理控制台的端口
  • 5672:RabbitMQ的消息发送处理接口

安装完成后,我们访问 http://ip:15672即可看到管理控制台。首次访问需要登录,默认的用户名和密码在配置文件中已经指定了。

登录后即可看到管理控制台总览页面:
image.png

RabbitMQ对应的架构如图:
image.png
其中包含几个概念:

  • publisher:生产者,也就是发送消息的一方
  • consumer:消费者,也就是消费消息的一方
  • queue:队列,存储消息。生产者投递的消息会暂存在消息队列中,等待消费者处理
  • exchange:交换机,负责消息路由。生产者发送的消息由交换机决定投递到哪个队列。
  • virtual host:虚拟主机,起到数据隔离的作用。每个虚拟主机相互独立,有各自的exchange、queue

2.2.收发消息

2.2.1.交换机

我们打开Exchanges选项卡,可以看到已经存在很多交换机:
image.png
我们点击任意交换机,即可进入交换机详情页面。仍然会利用控制台中的publish message 发送一条消息:
image.png
image.png
这里是由控制台模拟了生产者发送的消息。由于没有消费者存在,最终消息丢失了,这样说明交换机没有存储消息的能力

2.2.2.队列

我们打开Queues选项卡,新建一个队列:
image.png
命名为hello.queue1
image.png
再以相同的方式,创建一个队列,密码为hello.queue2,最终队列列表如下:
image.png
此时,我们再次向amq.fanout交换机发送一条消息。会发现消息依然没有到达队列!!

怎么回事呢?
发送到交换机的消息,只会路由到与其绑定的队列,因此仅仅创建队列是不够的,我们还需要将其与交换机绑定

2.2.3.绑定关系

点击Exchanges选项卡,点击amq.fanout交换机,进入交换机详情页,然后点击Bindings菜单,在表单中填写要绑定的队列名称:
image.png
相同的方式,将hello.queue2也绑定到改交换机。
最终,绑定结果如下:
image.png

2.2.4.发送消息

再次回到exchange页面,找到刚刚绑定的amq.fanout,点击进入详情页,再次发送一条消息:
image.png
回到Queues页面,可以发现hello.queue中已经有一条消息了:
image.png
点击队列名称,进入详情页,查看队列详情,这次我们点击get message:
image.png
可以看到消息到达队列了:
image.png
这个时候如果有消费者监听了MQ的hello.queue1hello.queue2队列,自然就能接收到消息了。

2.3.数据隔离

2.3.1.用户管理

点击Admin选项卡,首先会看到RabbitMQ控制台的用户管理界面:

在这里插入图片描述

这里的用户都是RabbitMQ的管理或运维人员。目前只有安装RabbitMQ时添加的liming这个用户。仔细观察用户表格中的字段,如下:

  • Nameliming,也就是用户名
  • Tagsadministrator,说明itheima用户是超级管理员,拥有所有权限
  • Can access virtual host/,可以访问的virtual host,这里的/是默认的virtual host

对于小型企业而言,出于成本考虑,我们通常只会搭建一套MQ集群,公司内的多个不同项目同时使用。这个时候为了避免互相干扰, 我们会利用virtual host的隔离特性,将不同项目隔离。一般会做两件事情:

  • 给每个项目创建独立的运维账号,将管理权限分离。
  • 给每个项目创建不同的virtual host,将每个项目的数据隔离。

比如,我们给门店营运项目创建一个新的用户,命名为sod

在这里插入图片描述

你会发现此时sod用户没有任何virtual host的访问权限:

在这里插入图片描述

别急,接下来我们就来授权。

2.3.2.virtual host(虚拟主机)

我们先退出登录:

在这里插入图片描述

切换到刚刚创建的sod用户登录,然后点击Virtual Hosts菜单,进入virtual host管理页:

在这里插入图片描述

可以看到目前只有一个默认的virtual host,名字为 /
我们可以给门店营运诊断项目创建一个单独的virtual host,而不是使用默认的/

在这里插入图片描述

创建完成后如图:

在这里插入图片描述

由于我们是登录sod账户后创建的virtual host,因此回到users菜单,你会发现当前用户已经具备了对/sod这个virtual host的访问权限了:

在这里插入图片描述

此时,点击页面右上角的virtual host下拉菜单,切换virtual host/sod

在这里插入图片描述

然后再次查看Queues选项卡,会发现之前的队列已经看不到了:

在这里插入图片描述

这就是基于virtual host 的隔离效果。

3.SpringAMQP

RabbitMQ使用AMQP协议,支持跨语言交互,官方提供了多种语言的客户端。在Java环境下,结合Spring框架使用Spring AMQP可以更加方便地进行消息收发,尤其是在生产环境中。Spring AMQP通过自动装配,与Spring Boot无缝集成,简化了RabbitMQ的使用。

SpringAmqp的官方地址:Spring AMQP

SpringAMQP提供了三个功能:

  • 自动声明队列、交换机及其绑定关系
  • 基于注解的监听器模式,异步接收消息
  • 封装了RabbitTemplate工具,用于发送消息

3.1.编写Demo工程

在课前资料给大家提供了一个Demo工程,方便我们学习SpringAMQP的使用:

包括三部分:

  • mq-demo:父工程,管理项目依赖
  • publisher:消息的发送者
  • consumer:消息的消费者

在mq-demo这个父工程中,已经配置好了SpringAMQP相关的依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.itcast.demo</groupId>
    <artifactId>mq-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>publisher</module>
        <module>consumer</module>
    </modules>
    <packaging>pom</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.12</version>
        <relativePath/>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--AMQP依赖,包含RabbitMQ-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>

因此,子工程中就可以直接使用SpringAMQP了。

3.2.快速入门

在之前的案例中,我们都是经过交换机发送消息到队列,不过有时候为了测试方便,我们也可以直接向队列发送消息,跳过交换机。
在入门案例中,我们就演示这样的简单模型,如图:

也就是:

  • publisher直接发送消息到队列
  • 消费者监听并处理队列中的消息

注意:这种模式一般测试使用,很少在生产中使用。

为了方便测试,我们现在控制台新建一个队列:simple.queue

在这里插入图片描述

添加成功:

在这里插入图片描述

3.1.1.消息发送

首先配置MQ地址,在publisher服务的application.yml中添加配置:

spring:
  rabbitmq:
    host: 47.108.181.66 # 你的服务器IP
    port: 5672 # 端口
    virtual-host: /sod # 虚拟主机
    username: sod # 用户名
    password: 123 # 密码

然后在publisher服务中编写测试类SpringAmqpTest,并利用RabbitTemplate实现消息发送:

package com.liming.publisher.amqp;

import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class SpringAmqpTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSimpleQueue() {
        // 队列名称
        String queueName = "simple.queue";
        // 消息
        String message = "hello, spring amqp!";
        // 发送消息
        rabbitTemplate.convertAndSend(queueName, message);
    }
}

打开控制台,可以看到消息已经发送到队列中:

在这里插入图片描述

3.1.2.消息接收

首先配置MQ地址,在consumer服务的application.yml中添加配置:

spring:
  rabbitmq:
    host: 47.108.181.66 # 你的服务器IP
    port: 5672 # 端口
    virtual-host: /sod # 虚拟主机
    username: sod # 用户名
    password: 123 # 密码

然后在consumer服务的com.liming.consumer.listener包中新建一个类SpringRabbitListener,代码如下:

package com.liming.consumer.listener;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class SpringRabbitListener {
    // 利用RabbitListener来声明要监听的队列信息
    // 将来一旦监听的队列中有了消息,就会推送给当前服务,调用当前方法,处理消息
    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(String msg) throws InterruptedException {
        System.out.println("spring 消费者接收到消息:【" + msg + "】");
    }
}

3.1.3.测试

启动consumer服务,然后在publisher服务中运行测试代码,发送MQ消息。最终consumer收到消息:

在这里插入图片描述

3.3.WorkQueues模型

Work queues,任务模型。简单来说就是让多个消费者绑定到一个队列,共同消费队列中的消息

当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。此时就可以使用work 模型,多个消费者共同处理消息处理,消息处理的速度就能大大提高了。

首先,我们在控制台创建一个新的队列,命名为work.queue

在这里插入图片描述

3.3.1.消息发送

这次我们循环发送,模拟大量消息堆积现象。在publisher服务中的SpringAmqpTest类中添加一个测试方法:

/**
 * workQueue
 * 向队列中不停发送消息,模拟消息堆积。
 */
@Test
public void testWorkQueue() throws InterruptedException {
    // 队列名称
    String queueName = "work.queue";
    // 消息
    String message = "hello, message_";
    for (int i = 0; i < 50; i++) {
        // 发送消息,每20毫秒发送一次,相当于每秒发送50条消息
        rabbitTemplate.convertAndSend(queueName, message + i);
        Thread.sleep(20);
    }
}

3.3.2.消息接收

要模拟多个消费者绑定同一个队列,我们在consumer服务的SpringRabbitListener中添加2个新的方法:

@RabbitListener(queues = "work.queue")
public void listenWorkQueue1(String msg) throws InterruptedException {
    System.out.println("消费者1接收到消息:【" + msg + "】" + LocalTime.now());
    Thread.sleep(20);
}

@RabbitListener(queues = "work.queue")
public void listenWorkQueue2(String msg) throws InterruptedException {
    System.err.println("消费者2........接收到消息:【" + msg + "】" + LocalTime.now());
    Thread.sleep(200);
}

注意到这两消费者,都设置了Thead.sleep,模拟任务耗时:

  • 消费者1 sleep了20毫秒,相当于每秒钟处理50个消息
  • 消费者2 sleep了200毫秒,相当于每秒处理5个消息

3.3.3.测试

启动ConsumerApplication后,在执行publisher服务中刚刚编写的发送测试方法testWorkQueue
最终结果如下:

消费者1接收到消息:【hello, message_0】11:24:35.347
消费者2接收到消息:【hello, message_1】11:24:35.363
消费者1接收到消息:【hello, message_2】11:24:35.394
消费者1接收到消息:【hello, message_4】11:24:35.457
消费者1接收到消息:【hello, message_6】11:24:35.523
消费者2接收到消息:【hello, message_3】11:24:35.567
消费者1接收到消息:【hello, message_8】11:24:35.598
消费者1接收到消息:【hello, message_10】11:24:35.645
消费者1接收到消息:【hello, message_12】11:24:35.708
消费者2接收到消息:【hello, message_5】11:24:35.771
消费者1接收到消息:【hello, message_14】11:24:35.771
消费者1接收到消息:【hello, message_16】11:24:35.834
消费者1接收到消息:【hello, message_18】11:24:35.896
消费者1接收到消息:【hello, message_20】11:24:35.960
消费者2接收到消息:【hello, message_7】11:24:35.975
消费者1接收到消息:【hello, message_22】11:24:36.024
消费者1接收到消息:【hello, message_24】11:24:36.085
消费者1接收到消息:【hello, message_26】11:24:36.148
消费者2接收到消息:【hello, message_9】11:24:36.179
消费者1接收到消息:【hello, message_28】11:24:36.210
消费者1接收到消息:【hello, message_30】11:24:36.273
消费者1接收到消息:【hello, message_32】11:24:36.336
消费者2接收到消息:【hello, message_11】11:24:36.383
消费者1接收到消息:【hello, message_34】11:24:36.399
消费者1接收到消息:【hello, message_36】11:24:36.462
消费者1接收到消息:【hello, message_38】11:24:36.525
消费者2接收到消息:【hello, message_13】11:24:36.587
消费者1接收到消息:【hello, message_40】11:24:36.587
消费者1接收到消息:【hello, message_42】11:24:36.651
消费者1接收到消息:【hello, message_44】11:24:36.713
消费者1接收到消息:【hello, message_46】11:24:36.776
消费者2接收到消息:【hello, message_15】11:24:36.792
消费者1接收到消息:【hello, message_48】11:24:36.839
消费者2接收到消息:【hello, message_17】11:24:36.996
消费者2接收到消息:【hello, message_19】11:24:37.204
消费者2接收到消息:【hello, message_21】11:24:37.408
消费者2接收到消息:【hello, message_23】11:24:37.612
消费者2接收到消息:【hello, message_25】11:24:37.816
消费者2接收到消息:【hello, message_27】11:24:38.020
消费者2接收到消息:【hello, message_29】11:24:38.224
消费者2接收到消息:【hello, message_31】11:24:38.429
消费者2接收到消息:【hello, message_33】11:24:38.633
消费者2接收到消息:【hello, message_35】11:24:38.837
消费者2接收到消息:【hello, message_37】11:24:39.041
消费者2接收到消息:【hello, message_39】11:24:39.245
消费者2接收到消息:【hello, message_41】11:24:39.449
消费者2接收到消息:【hello, message_43】11:24:39.654
消费者2接收到消息:【hello, message_45】11:24:39.858
消费者2接收到消息:【hello, message_47】11:24:40.062
消费者2接收到消息:【hello, message_49】11:24:40.267

可以看到消费者1消费者2竟然每人消费了25条消息:

  • 消费者1很快完成了自己的25条消息
  • 消费者2却在缓慢的处理自己的25条消息。

也就是说消息是平均分配给每个消费者,并没有考虑到消费者的处理能力。导致1个消费者空闲,另一个消费者忙的不可开交。没有充分利用每一个消费者的能力,最终消息处理的耗时远远超过了1秒。这样显然是有问题的。

3.3.4.能者多劳

在spring中有一个简单的配置,可以解决这个问题。我们修改consumer服务的application.yml文件,添加配置:

spring:
  rabbitmq:
    listener:
      simple:
        prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息

再次测试,发现结果如下:

消费者2接收到消息:【hello, message_0】11:28:27.766
消费者1接收到消息:【hello, message_1】11:28:27.798
消费者1接收到消息:【hello, message_2】11:28:27.845
消费者1接收到消息:【hello, message_3】11:28:27.897
消费者1接收到消息:【hello, message_4】11:28:27.939
消费者1接收到消息:【hello, message_6】11:28:27.986
消费者2接收到消息:【hello, message_5】11:28:27.986
消费者1接收到消息:【hello, message_7】11:28:28.033
消费者1接收到消息:【hello, message_8】11:28:28.080
消费者1接收到消息:【hello, message_9】11:28:28.128
消费者1接收到消息:【hello, message_10】11:28:28.175
消费者2接收到消息:【hello, message_11】11:28:28.206
消费者1接收到消息:【hello, message_12】11:28:28.222
消费者1接收到消息:【hello, message_13】11:28:28.269
消费者1接收到消息:【hello, message_14】11:28:28.316
消费者1接收到消息:【hello, message_15】11:28:28.363
消费者1接收到消息:【hello, message_16】11:28:28.410
消费者2接收到消息:【hello, message_17】11:28:28.426
消费者1接收到消息:【hello, message_18】11:28:28.457
消费者1接收到消息:【hello, message_19】11:28:28.520
消费者1接收到消息:【hello, message_20】11:28:28.567
消费者1接收到消息:【hello, message_21】11:28:28.614
消费者2接收到消息:【hello, message_22】11:28:28.661
消费者1接收到消息:【hello, message_23】11:28:28.661
消费者1接收到消息:【hello, message_24】11:28:28.708
消费者1接收到消息:【hello, message_25】11:28:28.755
消费者1接收到消息:【hello, message_26】11:28:28.803
消费者1接收到消息:【hello, message_27】11:28:28.850
消费者2接收到消息:【hello, message_28】11:28:28.881
消费者1接收到消息:【hello, message_29】11:28:28.900
消费者1接收到消息:【hello, message_30】11:28:28.944
消费者1接收到消息:【hello, message_31】11:28:28.991
消费者1接收到消息:【hello, message_32】11:28:29.038
消费者1接收到消息:【hello, message_33】11:28:29.085
消费者2接收到消息:【hello, message_34】11:28:29.100
消费者1接收到消息:【hello, message_35】11:28:29.132
消费者1接收到消息:【hello, message_36】11:28:29.179
消费者1接收到消息:【hello, message_37】11:28:29.226
消费者1接收到消息:【hello, message_38】11:28:29.273
消费者2接收到消息:【hello, message_39】11:28:29.320
消费者1接收到消息:【hello, message_40】11:28:29.320
消费者1接收到消息:【hello, message_41】11:28:29.367
消费者1接收到消息:【hello, message_42】11:28:29.478
消费者1接收到消息:【hello, message_43】11:28:29.525
消费者2接收到消息:【hello, message_44】11:28:29.540
消费者1接收到消息:【hello, message_45】11:28:29.572
消费者1接收到消息:【hello, message_46】11:28:29.619
消费者1接收到消息:【hello, message_47】11:28:29.666
消费者1接收到消息:【hello, message_48】11:28:29.713
消费者2接收到消息:【hello, message_49】11:28:29.761

可以发现,由于消费者1处理速度较快,所以处理了更多的消息;消费者2处理速度较慢,只处理了6条消息。而最终总的执行耗时也在1秒左右,大大提升。

3.3.5.总结

Work模型的使用:

  • 多个消费者绑定到一个队列,同一条消息只会被一个消费者处理
  • 通过设置prefetch来控制消费者预取的消息数量

3.4.交换机类型

在之前的两个测试案例中,都没有交换机,生产者直接发送消息到队列。而一旦引入交换机,消息发送的模式会有很大变化:


可以看到,在订阅模型中,多了一个exchange角色,而且过程略有变化:

  • Publisher:生产者,不再发送消息到队列中,而是发给交换机
  • Exchange:交换机,一方面,接收生产者发送的消息。另一方面,知道如何处理消息,例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作,取决于Exchange的类型。
  • Queue:消息队列也与以前一样,接收消息、缓存消息。不过队列一定要与交换机绑定。
  • Consumer:消费者,与以前一样,订阅队列,没有变化

Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange绑定,或者没有符合路由规则的队列,那么消息会丢失!

交换机的类型有四种:

  • Fanout:广播,将消息交给所有绑定到交换机的队列。我们最早在控制台使用的正是Fanout交换机
  • Direct:订阅,基于RoutingKey(路由key)发送给订阅了消息的队列
  • Topic:通配符订阅,与Direct类似,只不过RoutingKey可以使用通配符
  • Headers:头匹配,基于MQ的消息头匹配,用的较少。

3.5.Fanout交换机

Fanout,英文翻译是扇出,我觉得在MQ中叫广播更合适。在广播模式下,消息发送流程是这样的:

image.png

  • 1) 可以有多个队列
  • 2) 每个队列都要绑定到Exchange(交换机)
  • 3) 生产者发送的消息,只能发送到交换机
  • 4) 交换机把消息发送给绑定过的所有队列
  • 5) 订阅队列的消费者都能拿到消息

3.5.1.声明队列和交换机

在控制台创建队列fanout.queue1fanout.queue2:
在这里插入图片描述

然后再创建一个交换机:

在这里插入图片描述

然后绑定两个队列到交换机:

在这里插入图片描述

3.5.2.消息发送

publisher服务的SpringAmqpTest类中添加测试方法:

@Test
public void testFanoutExchange() {
    // 交换机名称
    String exchangeName = "sod.fanout";
    // 消息
    String message = "hello, everyone!";
    rabbitTemplate.convertAndSend(exchangeName, "", message);
}

3.5.3.消息接收

consumer服务的SpringRabbitListener中添加两个方法,作为消费者:

@RabbitListener(queues = "fanout.queue1")
public void listenFanoutQueue1(String msg) {
    System.out.println("消费者1接收到Fanout消息:【" + msg + "】");
}

@RabbitListener(queues = "fanout.queue2")
public void listenFanoutQueue2(String msg) {
    System.out.println("消费者2接收到Fanout消息:【" + msg + "】");
}

在这里插入图片描述

3.5.4.总结

交换机的作用是什么?

  • 接收publisher发送的消息
  • 将消息按照规则路由到与之绑定的队列
  • 不能缓存消息,路由失败,消息丢失
  • FanoutExchange的会将消息路由到每个绑定的队列

3.6.Direct交换机

在Fanout模式中,一条消息,会被所有订阅的队列都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。

image.png
在Direct模型下:

  • 队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由key)
  • 消息的发送方在 向 Exchange发送消息时,也必须指定消息的 RoutingKey
  • Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key进行判断,只有队列的Routingkey与消息的 Routing key完全一致,才会接收到消息

3.6.1.声明队列和交换机

首先在控制台声明两个队列direct.queue1direct.queue2
在这里插入图片描述

然后声明一个direct类型的交换机,命名为sod.direct:

在这里插入图片描述

然后使用redblue作为key,绑定direct.queue1direct.queue2sod.direct

在这里插入图片描述

3.6.2.消息接收

consumer服务的SpringRabbitListener中添加方法:

@RabbitListener(queues = "direct.queue1")
public void listenDirectQueue1(String msg) {
    System.out.println("消费者1接收到direct.queue1的消息:【" + msg + "】");
}

@RabbitListener(queues = "direct.queue2")
public void listenDirectQueue2(String msg) {
    System.out.println("消费者2接收到direct.queue2的消息:【" + msg + "】");
}

3.6.3.消息发送

publisher服务的SpringAmqpTest类中添加测试方法:

@Test
public void testSendDirectExchange() {
    // 交换机名称
    String exchangeName = "sod.direct";
    // 消息
    String message = "红色警报!日本乱排核废水,导致海洋生物变异,惊现哥斯拉!";
    // 发送消息
    rabbitTemplate.convertAndSend(exchangeName, "red", message);
}

由于使用的red这个key,所以两个消费者都收到了消息:

在这里插入图片描述

我们再切换为blue这个key:

@Test
public void testSendDirectExchange() {
    // 交换机名称
    String exchangeName = "sod.direct";
    // 消息
    String message = "最新报道,哥斯拉是居民自治巨型气球,虚惊一场!";
    // 发送消息
    rabbitTemplate.convertAndSend(exchangeName, "blue", message);
}

在这里插入图片描述

3.6.4.总结

描述下Direct交换机与Fanout交换机的差异?

  • Fanout交换机将消息路由给每一个与之绑定的队列
  • Direct交换机根据RoutingKey判断路由给哪个队列
  • 如果多个队列具有相同的RoutingKey,则与Fanout功能类似

3.7.Topic交换机

3.7.1.说明

Topic类型的ExchangeDirect相比,都是可以根据RoutingKey把消息路由到不同的队列。
只不过Topic类型Exchange可以让队列在绑定BindingKey 的时候使用通配符

BindingKey 一般都是有一个或多个单词组成,多个单词之间以.分割,例如: item.insert

通配符规则:

  • #:匹配一个或多个词
  • *:匹配不多不少恰好1个词

举例:

  • item.#:能够匹配item.spu.insert 或者 item.spu
  • item.*:只能匹配item.spu

图示:
image.png
假如此时publisher发送的消息使用的RoutingKey共有四种:

  • china.news 代表有中国的新闻消息;
  • china.weather 代表中国的天气消息;
  • japan.news 则代表日本新闻
  • japan.weather 代表日本的天气消息;

解释:

  • topic.queue1:绑定的是china.# ,凡是以 china.开头的routing key 都会被匹配到,包括:
    • china.news
    • china.weather
  • topic.queue2:绑定的是#.news ,凡是以 .news结尾的 routing key 都会被匹配。包括:
    • china.news
    • japan.news

首先,在控制台按照图示例子创建队列、交换机,并利用通配符绑定队列和交换机。此处步骤略。最终结果如下:

在这里插入图片描述

3.7.2.消息发送

publisher服务的SpringAmqpTest类中添加测试方法:

/**
 * topicExchange
 */
@Test
public void testSendTopicExchange() {
    // 交换机名称
    String exchangeName = "sod.topic";
    // 消息
    String message = "喜报!孙悟空大战哥斯拉,胜!";
    // 发送消息
    rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
}

3.7.3.消息接收

consumer服务的SpringRabbitListener中添加方法:

@RabbitListener(queues = "topic.queue1")
public void listenTopicQueue1(String msg){
    System.out.println("消费者1接收到topic.queue1的消息:【" + msg + "】");
}

@RabbitListener(queues = "topic.queue2")
public void listenTopicQueue2(String msg){
    System.out.println("消费者2接收到topic.queue2的消息:【" + msg + "】");
}

在这里插入图片描述

3.7.4.总结

描述下Direct交换机与Topic交换机的差异?

  • Topic交换机接收的消息RoutingKey必须是多个单词,以 . 分割
  • Topic交换机与队列绑定时的bindingKey可以指定通配符
  • #:代表0个或多个词
  • *:代表1个词

3.8.声明队列和交换机

在之前我们都是基于RabbitMQ控制台来创建队列、交换机。但是在实际开发时,队列和交换机是程序员定义的,将来项目上线,又要交给运维去创建。因此推荐的做法是由程序启动时检查队列和交换机是否存在,如果不存在自动创建。

3.8.1.基本API

SpringAMQP提供了一个Queue类,用来创建队列:
image.png

SpringAMQP还提供了一个Exchange接口,来表示所有不同类型的交换机:
image.png
我们可以自己创建队列和交换机,不过SpringAMQP还提供了ExchangeBuilder来简化这个过程:
image.png
而在绑定队列和交换机时,则需要使用BindingBuilder来创建Binding对象:
image.png

3.8.2.fanout示例

consumer中创建一个类,声明队列和交换机:

package com.liming.consumer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FanoutConfig {
    /**
     * 声明交换机
     * @return Fanout类型交换机
     */
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange("sod.fanout");
    }

    /**
     * 第1个队列
     */
    @Bean
    public Queue fanoutQueue1(){
        return new Queue("fanout.queue1");
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingQueue1(Queue fanoutQueue1, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
    }

    /**
     * 第2个队列
     */
    @Bean
    public Queue fanoutQueue2(){
        return new Queue("fanout.queue2");
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingQueue2(Queue fanoutQueue2, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
    }
}

3.8.2.direct示例

direct模式由于要绑定多个KEY,会非常麻烦,每一个Key都要编写一个binding:

package com.liming.consumer.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DirectConfig {

    /**
     * 声明交换机
     * @return Direct类型交换机
     */
    @Bean
    public DirectExchange directExchange(){
        return ExchangeBuilder.directExchange("sod.direct").build();
    }

    /**
     * 第1个队列
     */
    @Bean
    public Queue directQueue1(){
        return new Queue("direct.queue1");
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingQueue1WithRed(Queue directQueue1, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue1).to(directExchange).with("red");
    }
    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingQueue1WithBlue(Queue directQueue1, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue1).to(directExchange).with("blue");
    }

    /**
     * 第2个队列
     */
    @Bean
    public Queue directQueue2(){
        return new Queue("direct.queue2");
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingQueue2WithRed(Queue directQueue2, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue2).to(directExchange).with("red");
    }
    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingQueue2WithYellow(Queue directQueue2, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue2).to(directExchange).with("yellow");
    }
}

3.8.4.基于注解声明(推荐)

基于@Bean的方式声明队列和交换机比较麻烦,Spring还提供了基于注解方式来声明。

例如,我们同样声明Direct模式的交换机和队列:

@RabbitListener(bindings = @QueueBinding(
    value = @Queue(name = "direct.queue1"),
    exchange = @Exchange(name = "sod.direct", type = ExchangeTypes.DIRECT),
    key = {"red", "blue"}
))
public void listenDirectQueue1(String msg){
    System.out.println("消费者1接收到direct.queue1的消息:【" + msg + "】");
}

@RabbitListener(bindings = @QueueBinding(
    value = @Queue(name = "direct.queue2"),
    exchange = @Exchange(name = "sod.direct", type = ExchangeTypes.DIRECT),
    key = {"red", "yellow"}
))
public void listenDirectQueue2(String msg){
    System.out.println("消费者2接收到direct.queue2的消息:【" + msg + "】");
}

再试试Topic模式

@RabbitListener(bindings = @QueueBinding(
    value = @Queue(name = "topic.queue1"),
    exchange = @Exchange(name = "sod.topic", type = ExchangeTypes.TOPIC),
    key = "china.#"
))
public void listenTopicQueue1(String msg){
    System.out.println("消费者1接收到topic.queue1的消息:【" + msg + "】");
}

@RabbitListener(bindings = @QueueBinding(
    value = @Queue(name = "topic.queue2"),
    exchange = @Exchange(name = "sod.topic", type = ExchangeTypes.TOPIC),
    key = "#.news"
))
public void listenTopicQueue2(String msg){
    System.out.println("消费者2接收到topic.queue2的消息:【" + msg + "】");
}

3.9.消息转换器

Spring的消息发送代码接收的消息体是一个Object:
image.png

而在数据传输时,它会把你发送的消息序列化为字节发送给MQ,接收消息的时候,还会把字节反序列化为Java对象。只不过,默认情况下Spring采用的序列化方式是JDK序列化

众所周知,JDK序列化存在下列问题:

  • 数据体积过大
  • 有安全漏洞
  • 可读性差

3.9.1.测试默认转换器

  • 创建测试队列

首先,我们在consumer服务中声明一个新的配置类,利用@Bean的方式创建一个队列

在这里插入图片描述

具体代码:

package com.liming.consumer.config;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MessageConfig {

    @Bean
    public Queue objectQueue() {
        return new Queue("object.queue");
    }
}

重启consumer服务以后,该队列就会被自动创建出来了:
在这里插入图片描述

  • 发送消息

我们在publisher模块的SpringAmqpTest中新增一个消息发送的代码,发送一个Map对象:

@Test
public void testSendMap() throws InterruptedException {
    // 准备消息
    Map<String,Object> msg = new HashMap<>();
    msg.put("name", "柳岩");
    msg.put("age", 21);
    // 发送消息
    rabbitTemplate.convertAndSend("object.queue", msg);
}

发送消息后查看控制台:
image.png
可以看到消息格式非常不友好。

3.9.2.配置JSON转换器

显然,JDK序列化方式并不合适。我们希望消息体的体积更小、可读性更高,因此可以使用JSON方式来做序列化和反序列化。

publisherconsumer两个服务中都引入依赖:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.10</version>
</dependency>

注意,如果项目中引入了spring-boot-starter-web依赖,则无需再次引入Jackson依赖

配置消息转换器,在publisherconsumer两个服务的启动类中添加一个Bean即可:

@Bean
public MessageConverter messageConverter(){
    // 1.定义消息转换器
    Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
    // 2.配置自动创建消息id,用于识别不同消息,也可以在业务中基于ID判断是否是重复消息
    jackson2JsonMessageConverter.setCreateMessageIds(true);
    return jackson2JsonMessageConverter;
}

消息转换器中添加的messageId可以便于我们将来做幂等性判断。

此时,我们到MQ控制台删除object.queue中的旧的消息。然后再次执行刚才的消息发送的代码,到MQ的控制台查看消息结构:
image.png

3.9.3.消费者接收Object

我们在consumer服务中定义一个新的消费者,publisher是用Map发送,那么消费者也一定要用Map接收,格式如下:

@RabbitListener(queues = "object.queue")
public void listenSimpleQueueMessage(Map<String, Object> msg) throws InterruptedException {
    System.out.println("消费者接收到object.queue消息:【" + msg + "】");
}

在这里插入图片描述

  • 27
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小钟不想敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值