RabbitMQ 简介与基本使用(附代码)

提到各种消息中间件的用处,首先想到的是异步调用,那同步调用到底有什么短处呢?

  • 耦合度高:每次加入新的需求,都要修改原来的代码
  • 性能较低:调用者需等待提供者响应,总请求耗时取决于各个服务耗时,会导致资源的长时间占用
  • 级联失败:提供者出现问题,所有调用方都会跟着出问题,导致整个微服务群故障

这便引出了异步调用模式,较为成熟的要数事件驱动模式异步调用
在这里插入图片描述

  • 服务解耦:根据订阅与否决定是否执行提供者代码,无需修改调用者代码
  • 性能提升:调用者只需要发布事件,无需等待提供者响应
  • 避免了级联失败
  • 流量削峰:Broker 可起到缓冲作用,将提供者服务的瞬间高并发访问削减成长时间的低并发
  • 缺点:Broker 要有足够强的可靠性;架构复杂,业务流程不明显,不好追踪管理

RabbitMQ 就起到了上面事件驱动模式异步调用模式中 Broker 的作用,其整体架构如下
在这里插入图片描述

  • channel :通道,操作 MQ 的具体对象
  • exchange :交换机,用于将消息路由到队列中
  • queue :消息队列,用于缓存消息、等待 consumer 获取消息进行消费
  • virtualHost :虚拟主机,是对 queue 、exchange 等资源的逻辑分组

基本队列模型的使用

基本队列模型图如下
在这里插入图片描述

  • publisher :消息生产者,将消息发送到 queue
  • queue :消息队列,接收并缓存消息
  • consumer :消息消费者,处理 queue 中的消息

代码实现

  1. 父工程依赖
<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>

<properties>
    <spring-boot-dependencies>2.3.9.RELEASE</spring-boot-dependencies>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot-dependencies}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
  1. consumer 模块
<parent>
    <artifactId>mq-demo</artifactId>
    <groupId>cn.itcast.demo</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>consumer</artifactId>

<dependencies>
    <!--AMQP依赖,包含RabbitMQ-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
</dependencies>
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 建立连接
        ConnectionFactory factory = new ConnectionFactory();
        // 1.1. 设置连接参数,分别是:主机名、端口号、VirtualHost 、用户名、密码
        factory.setHost("192.168.255.128");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("itcast");
        factory.setPassword("123321");
        // 1.2. 建立连接
        Connection connection = factory.newConnection();

        // 2. 创建通道
        Channel channel = connection.createChannel();

        // 3. 创建队列 simple.queue
        String queueName = "simple.queue";
        channel.queueDeclare(queueName, false, false, false, null);

        // 4. 订阅 simple.queue 队列的消息(异步的)
        channel.basicConsume(queueName, true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                   AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 5. 处理消息
                String message = new String(body);
                System.out.println("接收到消息:【" + message + "】");
            }
        });
        System.out.println("等待接收消息。。。。");
    }
}
  1. publisher 模块
<parent>
    <artifactId>mq-demo</artifactId>
    <groupId>cn.itcast.demo</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>publisher</artifactId>

<dependencies>
    <!--AMQP依赖,包含RabbitMQ-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
</dependencies>
@SpringBootApplication
public class PublisherApplication {
    public static void main(String[] args) {
        SpringApplication.run(PublisherApplication.class);
    }
}

public class Publisher {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 建立连接
        ConnectionFactory factory = new ConnectionFactory();
        // 1.1. 设置连接参数,分别是:主机名、端口号、vhost、用户名、密码
        factory.setHost("192.168.255.128");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("itcast");
        factory.setPassword("123321");
        // 1.2. 建立连接
        Connection connection = factory.newConnection();

        // 2. 创建通道 Channel
        Channel channel = connection.createChannel();

        // 3. 创建队列 simple.queue
        String queueName = "simple.queue";
        channel.queueDeclare(queueName, false, false, false, null);

        // 4.发送消息
        String message = "hello, rabbitmq!";
        channel.basicPublish("", queueName, null, message.getBytes());
        System.out.println("发送消息成功:【" + message + "】");

        // 5.关闭通道和连接
        channel.close();
        connection.close();
    }
}
  1. 启动 Publisher 和 Consumer 类,谁先启动无所谓。如果是 Publisher 先启动,则会先向 simple.queue 队列发送一条消息,直到 Consumer 启动后消息被消费;Consumer 启动后会一直处于运行状态,监听消息的到来
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值