<RabbitMQ, SpringAMQP> [初阶] - 从概念到实战系统讲解,带你领略服务异步通讯的魅力

目录

一、MQ

1.1、同步通讯

同步调用方案的优缺点

1.2、异步通讯

异步调用方案的优缺点

1.3、什么是 MQ?

1.4、常见的消息模型

二、SpringAMQP

2.1、概念

2.2、案例实现

2.2.1、SpringAMQP 实现基础消息队列(BasicQueue)

2.2.2、SpringAMQP 实现工作消息队列((Work Queue)

2.2.3、SpringAMQP 实现广播交换机消息队列(Fanout Exchange)

2.2.4、Spring AMQP 实现路由交换机消息队列(Direct Exchange)

2.2.5、SpringAMQP 实现主题交换机消息模型(Topic Exchange)

2.3、 SpringAMQP 消息转换器

2.3.1、JDK ObjectOutputStream 序列化数据

2.3.2、JSON 序列化数据

1.引入依赖

2.在服务生产者和消费者中都重新定义一个 MessageConverter,注入到 Spring 容器中


一、MQ


1.1、同步通讯

当调用者发送请求以后,必须要等到服务提供者响应以后才可以发送下一个请求(微服务间基于Feign的调用就属于同步方式)

这就像是你想和多个妹子同时聊天,但是你给第一个妹子发完消息以后非要等到她回复了以后你才继续向下一个妹子发送消息,虽然你能第一时间得到第一个妹子的回复,但是你聊天的效率,吞吐量大大下降了~

同步调用方案的优缺点

优点如下:

  1. 时效性强,可以立即得到结果。

缺点如下:

  1. 耦合度高:每次加入新的需求,都要修改原来的代码(远程调用代码);
  2. 性能下降:调用者需要等待服务提供者响应,如果调用链过长则响应时间等于每次调用的时间之和;
  3. 资源浪费:调用链中的每个服务在等待响应过程中,不能释放请求占用的资源,高并发场景下会极度浪费系统资源;
  4. 级联失败:如果服务提供者出现问题,所有调用方都会跟着出问题,如同多米诺骨牌一样,迅速导致整个微服务群故障

1.2、异步通讯

调用者不直接与服务提供者交互,而是调用者将调用事件交由给事件代理者(Broker),由他来通知订阅者谁需要来提供服务了,这样调用者无需等待服务提供者的响应,继续进行下个调用。

异步调用常见实现就是事件驱动模式,不同于之前同步调用的那种方式一样先后调用其他多个服务,所以我们引入了Broker,Broker也就是事件代理者,在我们系统中只要有人发起请求就是一个事件,这个事件就叫给Broker去管理;我们的其他微服务通过去订阅Broker,就好比你关注了微信公众号一样,只要有消息就会推送给你。

异步调用方案的优缺点

优点如下:

  1. 耦合度低:当有新的需要来了,不用再去修改原来的代码(远程调用代码),而是直接通过Broker 广播通知订阅了他的服务;
  2. 吞吐量提升:调用者无需等到服务提供者响应,就可以继续发送请求。
  3. 故障隔离:当服务其提供者其中有一个挂掉时,不会像同步通讯影响到其他微服务,我们只需要修复当前这一个挂掉的微服务,重启即可。
  4. 流量削峰:当业务越来越多,而我们的其他微服务只能每秒处理一个请求,这时候如果突然有大量的请求来临,就可以通过 Broker 来缓冲,其他微服务根据自己的处理能力来处理即可,最后将一个高并发就被砍平了变成了低并发。

缺点如下:

  1. 依赖于Broker的可靠性、安全性、吞吐能力,一旦 Broker 挂掉,整个业务也就挂掉了
  2. 架构复杂了,业务没有明显的流程线,不好追踪管理

1.3、什么是 MQ?

MQMessageQueue),中文是消息队列,字面来看就是存放消息的队列。也就是事件驱动架构中的Broker

Ps:以下区别面试可能会考

而本篇主要讲解的就是 RabbitMQ ,他是是基于Erlang语言开发的开源消息通信中间件,官网地址:RabbitMQ: easy to use, flexible messaging and streaming — RabbitMQ

关于 RabbitMQ 的安装,可以参考以下文章:

http://t.csdn.cn/SaYYl

1.4、常见的消息模型

MQ的官方文档中给出了5个MQ的Demo示例,对应了几种不同的用法:

  1. 基本消息队列(BasicQueue)
  2. 工作消息队列(WorkQueue)

发布订阅(Publish、Subscribe),又根据交换机类型不同分为三种:

  1. Fanout Exchange:广播
  2. Direct Exchange:路由
  3. Topic Exchange:主题

接下来就通过 SpringAMQP 来实现一下这 5 种消息模型~

二、SpringAMQP


2.1、概念

什么是 AMQP?

全称 Advanced Message Queuing Protocol,是用于在应用程序之间传递业务消息的开放标准。该协议与语言和平台无关,更符合微服务中独立性的要求

什么是 SpringAMQP?

Spring AMQP是基于AMQP协议定义的一套API规范,提供了模板用来发送和接收消息。包含两部分,其中spring-amqp是基础抽象,spring-rabbit是底层的默认实现。

2.2、案例实现

2.2.1、SpringAMQP 实现基础消息队列(BasicQueue)

首先服务生产者 publisher:

a)由于生产者和消费者服务都需要 amqp 依赖,因此这里直接将依赖放到父工程中

<!--AMQP依赖,包含RabbitMQ-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

b)在 publisher (消息发送)服务中编写application.yml,添加mq连接信息:

spring:
  rabbitmq:
    host: 193.168.150.185 # 主机名
    port: 5672 # 端口
    virtual-host: / # 虚拟主机 
    username: root # 用户名
    password: 1234 # 密码

Ps:云服务器记得放行 5672 端口!!!

c)publisher服务中新建一个测试类,编写测试方法:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAMQPTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSendMessageSimpleQueue() {
        String queueName = "simple.queue";
        String message = "hello, spring amqp!";
        rabbitTemplate.convertAndSend(queueName, message);
    }

}

以上可得知 SpringAMQP 发送消息需要实现以下几点: 

  1. 引入 amqp 的 starter 依赖;
  2. 配置 RabbitMQ 地址;
  3. 利用 RabbitTemplate 的 convertAndSend 方法来指定队列发送消息

接着是服务消费者 consumer:

a)在consumer服务中编写application.yml,添加mq连接信息:

spring:
  rabbitmq:
    host: 193.168.150.185 # 主机名
    port: 5672 # 端口
    virtual-host: / # 虚拟主机 
    username: root # 用户名
    password: 1234 # 密码

b)consumer服务中新建一个类,编写消费逻辑:

@Component
public class SpringRabbitListener {

    @RabbitListener(queues = "simple.queue")
    public void ListenQueue(String msg) {
        System.out.println("消费者接收到 simple.queue 的消息:" + msg);
    }

}

以上可得知 SpringAMQP 接收消息需要实现以下几点: 

  1. 引入amqp的starter依赖
  2. 配置RabbitMQ地址
  3. 定义类,添加@Component注解
  4. 类中声明方法,添加@RabbitListener注解,方法参数就时消息

Ps:消息一旦消费就会从队列删除,RabbitMQ没有消息回溯功能

最终执行效果如下:

2.2.2、SpringAMQP 实现工作消息队列((Work Queue)

Work queue工作队列,可以提高消息处理速度,避免队列消息堆积;

遇到的问题:当消息进入 queue 时,消费者1 和 消费者2 都会先做一个操作叫做“消息预取”,也就是先取消息,但不执行操作,等从 queue 中拿完(如果不设置,默认是无限次拿)了以后再执行具体的消费操作,但这样会导致一个问题——当 消费者1 的消费处理速度是 消费者2 处理速度的两倍时,但是由于“消息预取”,他们两都会取到相等的消息数量,因此就会导致 消费者1 提前处理完,消费者2 还有很多没有处理的情况,降低了总体处理的效率。

解决办法:为了解决这种问题的发生,也可以通过修改消息预取的数量,设置为 1 ,就是拿一个处理完了以后再取下一个,就可以避免以上问题(设置为1,就是根据自身处理能力,拿去相应的数据)。

具体实现如下

a)在 publisher 服务中添加一个测试方法,循环发送 50 条消息到 simple.queue 队列(控制时间为1秒内发送完)

    @Test
    public void testSendMessageWorkQueue() throws InterruptedException {
        String queueName = "simple.queue";
        String message = "hello, workQueue!";
        for(int i = 0; i < 50; i++) {
            rabbitTemplate.convertAndSend(queueName, message + i);
            Thread.sleep(20);
        }
    }

b)consumer服务中创建两个消费者,也监听simple.queue

@Component
public class SpringRabbitListener {

    @RabbitListener(queues = "simple.queue")
    public void ListenQueue(String msg) throws InterruptedException {
        System.err.println("消费者接收到 simple.queue 的消息:" + msg + LocalDate.now());
        Thread.sleep(100);
    }

    @RabbitListener(queues = "simple.queue")
    public void ListenQueue2(String msg) throws InterruptedException {
        System.out.println("消费者接收到 simple.queue 的消息:" + msg + LocalDate.now());
        Thread.sleep(25);
    }

}

c)消费预取限制:修改application.yml文件,设置preFetch这个值,可以控制预取消息的上限

logging:
  pattern:
    dateformat: MM-dd HH:mm:ss:SSS
spring:
  rabbitmq:
    host: 170.193.116.135
    port: 5672
    username: root
    password: 1234
    virtual-host: /
    listener:
      simple:
        prefetch: 1

执行结果如下: 

2.2.3、SpringAMQP 实现广播交换机消息队列(Fanout Exchange)

发布订阅模式与之前案例的区别就是允许将同一消息发送给多个消费者。实现方式是加入了exchange(交换机)。

常见exchange类型包括:

1. Fanout:广播
2. Direct:路由
3. Topic:话题

这里我们先来理解一下广播消息队列模型~

Fanout Exchange:会将接收到的消息广播到每一个跟其绑定的queue,最后交给对应的消费者,值得注意的是,exchange负责消息路由,而不是存储,路由失败则消息丢失。

具体实现如下:

a)在consumer服务创建一个类,添加@Configuration注解,创建队列和交换机,并声明FanoutExchangeQueue和绑定关系对象 Binding ,绑定方式是 BindingBuilder.bind(队列).to(交换机)

package cn.itcast.mq.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 {

    //itcast.fanout
    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange("itcast.fanout");
    }

    //itcast.queue1
    @Bean
    public Queue fanoutQueue1() {
        return new Queue("fanout.queue1");
    }

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

    //itcast.queue2
    @Bean
    public Queue fanoutQueue2() {
        return new Queue("fanout.queue2");
    }

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

}

b)运行以后可以通过 RabbitMQ 客户端看到以下绑定情况:

 

c)添加测试方法

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAMQPTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testFanoutMessage() {
        String exchangeName = "itcast.fanout";
        String message = "hello! fanout";
        rabbitTemplate.convertAndSend(exchangeName, "", message);
    }

}

d)这里一个交换机绑定了两个队列,因此运行结果如下 :

2.2.4、Spring AMQP 实现路由交换机消息队列(Direct Exchange)

 Direct Exchange 会将接收到的消息根据规则路由到指定的Queue,因此称为路由模式(routes),通常一个 Queue 都会与 Exchange 设置一个 BindingKey,发布者发送消息时会先指定 RoutingKey,这时交换机就会将消息路由到 BindingKey 与消息 RoutingKey 一致的队列。

具体实现如下:

a)在consumer服务中,编写两个消费者方法,分别监听direct.queue1和direct.queue2,并利用@RabbitListener声明Queue、Exchange、BoutingKey
 

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue1"), //绑定队列
            exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT), //绑定交换机,type 可以不写,默认为 Direct
            key = {"java", "C++"} // Bindingkey
    ))
    public void listenDirectQueue1(String msg) {
        System.out.println("消费者 1 收到 Direct 消息:" + msg);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue2"), //绑定队列
            exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT), //绑定交换机,type 可以不写,默认为 Direct
            key = {"java", "GO"} // Bindingkey
    ))
    public void listenDirectQueue2(String msg) {
        System.out.println("消费者 2 收到 Direct 消息:" + msg);
    }

b)运行后可以观察绑定情况:

c)编写测试方法:

    @Test
    public void testDirectMessage() {
        String exchangeName = "itcast.direct";
        String message = "hello! direct";
        rabbitTemplate.convertAndSend(exchangeName, "C++", message);
    }

d)运行结果如下:

2.2.5、SpringAMQP 实现主题交换机消息模型(Topic Exchange)

TopicExchange 与 DirectExchange 十分类似,区别在于routingKey必须是多个单词的列表,并且以 . 分割。

QueueExchange指定BindingKey时可以使用以下通配符:

#:代指0个或多个单词
*:代指一个单词

例如: china.# 就相当于 china.new 或者 china.difa 或者 china.alhglag ......等等一切情况

具体实现如下(这里不具体说明了,除了通配符差异,用法跟 Direct 消息队列一模一样~):

@Component
public class SpringRabbitListener {

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

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

}

    @Test
    public void testTopicMessage() {
        String exchangeName = "itcast.topic";
        String message = "hello! topic";
        rabbitTemplate.convertAndSend(exchangeName, "china.good", message);
    }

运行结果:

2.3、 SpringAMQP 消息转换器

2.3.1、JDK ObjectOutputStream 序列化数据

在SpringAMQP的发送方法中,接收消息的类型是Object,也就是说我们可以发送任意对象类型的消息,接下来做个小实验

如下,注入一个队列到容器中,接着在提供一个服务生产者供测试,发送一个对象数据,观察 RabbitMQ 客户端队列数据形式

@Configuration
public class FanoutConfig {

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

}
    @Test
    public void testObjectMessage() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("国家", "china");
        rabbitTemplate.convertAndSend("object.queue", map);
    }

 运行后,查看 RabbitMQ 队列数据如下:

为什么发送的消息变成了这个样子呢?

这是因为SpringAMQP会帮我们序列化为字节后发送:Spring的对消息对象的处理是由org.springframework.amqp.support.converter.MessageConverter 来处理的。而默认实现是SimpleMessageConverter,基于JDK的ObjectOutputStream完成序列化。 

但是这样的数据就有可能引发以下两种问题:

  1. 转化后数据过长,影响传输效率。
  2. 容易引发 sql 注入问题。

2.3.2、JSON 序列化数据

我们只需要在服务生产者和消费者的 Spring 启动类中都重新定义一个 MessageConverter 类型的Bean即可。这里推荐用JSON方式序列化~

具体步骤如下:

1.引入依赖

因为服务生产者和服务消费者都需要 JSON 来序列化和反序列化,因此直接在的父类中引入依赖即可

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

2.在服务生产者和消费者中都重新定义一个 MessageConverter,注入到 Spring 容器中

使用 @Bean 注解注入即可

@SpringBootApplication
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

}
@SpringBootApplication
public class PublisherApplication {
    public static void main(String[] args) {
        SpringApplication.run(PublisherApplication.class);
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
    
}

再尝试发送数据,结果如下:

Ps:注意发送方与接收方必须使用相同的MessageConverter

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

陈亦康

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

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

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

打赏作者

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

抵扣说明:

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

余额充值