RabbitMQ笔记1(基础知识)

RabbitMQ 实战教程

1.MQ引言

1.1 什么是MQ

MQ(Message Quene) : 消息队列(消息中间件),通过典型的 生产者消费者模型,生产者不断向消息队列中生产消息,消费者不断的从队列中获取消息。

因为消息的生产和消费都是异步的,而且只关心消息的发送和接收,没有业务逻辑的侵入,可以轻松的实现系统间解耦。

通过利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成。

异步,解耦,削峰

1.2 MQ有哪些

当今市面上有很多主流的消息中间件

  • 老牌的ActiveMQRabbitMQ
  • 热门的Kafka
  • 阿里巴巴自主开发RocketMQ

1.3 不同MQ特点

  1. ActiveMQ
    ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。它是一个完全支持JMS规范的的消息中间件。丰富的API,多种集群架构模式让ActiveMQ在业界成为老牌的消息中间件,在中小型企业颇受欢迎。API较为完善。缺点:性能,吞吐量较小!

  2. Kafka
    Kafka是LinkedIn开源的分布式发布-订阅消息系统,目前归属于Apache顶级项目。Kafka主要特点是基于Pull的模式来处理消息消费, 追求高吞吐量,一开始的目的就是用于日志收集和传输。0.8版本开始支持复制,不支持事务,对消息的重复、丢失、错误没有严格要求。
    适合产生大量数据的互联网服务的数据收集业务。追求效率。

  3. RocketMQ
    RocketMQ是阿里开源的消息中间件,它是纯Java开发,具有高吞吐量、高可用性、适合大规模分布式系统应用的特点。RocketMQ思路起源于Kafka,但并不是Kafka的一个Copy,它对消息的可靠传输及事务性做了优化,目前在阿里集团被广泛应用于交易、充值、流计算、消息推送、日志流式处理、binglog分发等场景。开源的未支持分布式事务。要是用需要收费

  4. RabbitMQ
    RabbitMQ是使用Erlang语言开发的开源消息队列系统,基于AMQP协议来实现。AMQP的主要特征是面向消息、队列、路由(包括点对点和发布/订阅)、可靠性、安全。AMQP协议更多用在企业系统内对数据一致性、稳定性和可靠性要求很高的场景,对性能和吞吐量的要求还在其次。RabbitMQ可以与spring无缝衔接!
    RabbitMQ比Kafka可靠,Kafka效率远高于RabbitMQ,因此Kafka更适合IO高吞吐的处理,一般应用在大数据日志处理或对实时性(少量延迟),可靠性(少量丢数据)要求稍低的场景使用,比如ELK日志收集。


2.RabbitMQ 的引言

2.1 RabbitMQ

基于AMQP协议,erlang语言开发,是部署最广泛的开源消息中间件,是最受欢迎的开源消息中间件之一。

优点:spring无缝整合RabbitMQ,错误处理友好,几乎不丢失数据!
在这里插入图片描述

官网: https://www.rabbitmq.com/

官方教程: https://www.rabbitmq.com/#getstarted

  • AMQP 协议
    AMQP(advanced message queuing protocol)在2003年时被提出,最早用于解决金融领不同平台之间的消息传递交互问题。顾名思义,AMQP是一种协议,更准确的说是一种binary wire-level protocol(链接协议)。这是其和JMS的本质差别,AMQP不从API层进行限定,而是直接定义网络交换的数据格式。这使得实现了AMQP的provider天然性就是跨平台的。以下是AMQP协议模型:

在这里插入图片描述

2.2 RabbitMQ 的安装

2.2.1 下载

官网下载地址: https://www.rabbitmq.com/download.html[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GxBzSjkG-1610726893672)(RibbitMQ 实战教程.assets/image-20190925220115235.png)]

最新版本: 3.7.18

2.2.2 下载的安装包[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BULOAcrU-1610726893674)(RibbitMQ 实战教程.assets/image-20190925220343521.png)]

注意:这里的安装包是centos7安装的包

2.2.3 安装步骤
  1. 将rabbitmq安装包上传到linux系统中
    erlang-22.0.7-1.el7.x86_64.rpm
    rabbitmq-server-3.7.18-1.el7.noarch.rpm
    socat-1.7.3.2-2.el7.x86_64.rpm

  2. 安装Erlang依赖包
    rpm -ivh erlang-22.0.7-1.el7.x86_64.rpm
    或者
    yum install erlang
    安装内存管理
    yum install socat

  3. 安装RabbitMQ安装包(需要联网)
    yum install -y rabbitmq-server-3.7.18-1.el7.noarch.rpm
    注意:默认安装完成后配置文件模板在:/usr/share/doc/rabbitmq-server-3.7.18/rabbitmq.config.example目录中,需要将配置文件复制到/etc/rabbitmq/目录中,并修改名称为rabbitmq.config

  4. 复制配置文件
    cp /usr/share/doc/rabbitmq-server-3.7.18/rabbitmq.config.example /etc/rabbitmq/rabbitmq.config
    搜索文件
    find / -name rabbit.config.exapmle

[root@liushuipiaoxiang rabbitmq]# find / -name rabbitmq.config.example
/usr/share/doc/rabbitmq-server-3.7.18/rabbitmq.config.example
  1. 查看配置文件位置
    ls /etc/rabbitmq/rabbitmq.config

  2. 修改配置文件(参见下图:)
    vim /etc/rabbitmq/rabbitmq.config

设置允许来宾访问:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wEawUh6D-1610726893677)(RibbitMQ 实战教程.assets/image-20190925222230260-3836271.png)]

将上图中配置文件中红色部分去掉%%,以及最后的,逗号 修改为下图:
在这里插入图片描述

  1. 执行如下命令,启动rabbitmq中的插件管理
    rabbitmq-plugins enable rabbitmq_management
    出现如下说明:
[root@liushuipiaoxiang rabbitmq]# rabbitmq-plugins enable rabbitmq_management
Enabling plugins on node rabbit@liushuipiaoxiang:
rabbitmq_management
The following plugins have been configured:
  rabbitmq_management
  rabbitmq_management_agent
  rabbitmq_web_dispatch
Applying plugin configuration to rabbit@liushuipiaoxiang...
The following plugins have been enabled:
  rabbitmq_management
  rabbitmq_management_agent
  rabbitmq_web_dispatch

set 3 plugins.
Offline change; changes will take effect at broker restart.

  1. 启动RabbitMQ的服务
    systemctl start rabbitmq-server
    systemctl restart rabbitmq-server
    systemctl stop rabbitmq-server

  2. 查看服务状态
    systemctl status rabbitmq-server

  3. 关闭防火墙服务
    systemctl disable firewalld
    Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
    Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
    systemctl stop firewalld

  4. 访问web管理界面
    http://10.15.0.1:15672/

  5. 登录管理界面
    username: guest
    password: guest
    在这里插入图片描述

[root@liushuipiaoxiang ~]# curl localhost:15672
<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<html>
  <head>
    <title>RabbitMQ Management</title>
    <script src="js/ejs-1.0.min.js" type="text/javascript"></script>
    <script src="js/jquery-3.4.1.min.js"></script>
    <script src="js/jquery.flot-0.8.1.min.js" type="text/javascript"></script>
    <script src="js/jquery.flot-0.8.1.time.min.js" type="text/javascript"></script>
    <script src="js/sammy-0.7.6.min.js" type="text/javascript"></script>
    <script src="js/json2-2016.10.28.js" type="text/javascript"></script>
    <script src="js/base64.js" type="text/javascript"></script>
    <script src="js/global.js" type="text/javascript"></script>
    <script src="js/main.js" type="text/javascript"></script>
    <script src="js/prefs.js" type="text/javascript"></script>
    <script src="js/formatters.js" type="text/javascript"></script>
    <script src="js/charts.js" type="text/javascript"></script>

    <link href="css/main.css" rel="stylesheet" type="text/css"/>
    <link href="favicon.ico" rel="shortcut icon" type="image/x-icon"/>

<!--[if lte IE 8]>
    <script src="js/excanvas.min.js" type="text/javascript"></script>
    <link href="css/evil.css" rel="stylesheet" type="text/css"/>
<![endif]-->
  </head>
  <body>
    <div id="outer"></div>
    <div id="debug"></div>
    <div id="scratch"></div>
  </body>
</html>

3. RabiitMQ 配置

3.1RabbitMQ 管理命令行

  1. 服务启动相关
    systemctl start rabbitmq-server
    systemctl restart rabbitmq-server
    systemctl stop rabbitmq-server
    systemctl status rabbitmq-server

  2. 管理命令行
    用来在不使用web管理界面情况下命令操作RabbitMQ
    rabbitmqctl help 可以查看更多命令
    如查看用户

[root@liushuipiaoxiang ~]# rabbitmqctl list_users;
Listing users ...
user    tags
guest   [administrator]
  1. 插件管理命令行
    rabbitmq-plugins enable|list|disable
[root@liushuipiaoxiang ~]# rabbitmqctl list_users;
Listing users ...
user    tags
guest   [administrator]
[root@liushuipiaoxiang ~]# rabbitmq-plugins

[root@liushuipiaoxiang ~]# rabbitmq-plugins list

主要还是页面操作,但是也会用命令行操作

3.2 web管理界面介绍

3.2.1 overview概览

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hdrwUylf-1610726893683)(RibbitMQ 实战教程.assets/image-20191126162026720.png)]

  • connections:无论生产者还是消费者,都需要与RabbitMQ建立连接后才可以完成消息的生产和消费,在这里可以查看连接情况

  • channels:通道,建立连接后,会形成通道,消息的投递获取依赖通道。

  • Exchanges:交换机,用来实现消息的路由

  • Queues:队列,即消息队列,消息存放在队列中,等待消费,消费后被移除队列。

3.2.2 Admin用户和虚拟主机管理

在这里插入图片描述
在这里插入图片描述

  1. 添加用户

在这里插入图片描述

上面的Tags选项,其实是指定用户的角色,可选的有以下几个:

  • 超级管理员(administrator)

    可登陆管理控制台,可查看所有的信息,并且可以对用户,策略(policy)进行操作。

  • 监控者(monitoring)

    可登陆管理控制台,同时可以查看rabbitmq节点的相关信息(进程数,内存使用情况,磁盘使用情况等)

  • 策略制定者(policymaker)

    可登陆管理控制台, 同时可以对policy进行管理。但无法查看节点的相关信息(上图红框标识的部分)。

  • 普通管理者(management)

    仅可登陆管理控制台,无法看到节点信息,也无法对策略进行管理。

  • 其他

    无法登陆管理控制台,通常就是普通的生产者和消费者。

  1. 创建虚拟主机
  • 虚拟主机
    为了让各个用户可以互不干扰的工作,RabbitMQ添加了虚拟主机(Virtual Hosts)的概念。其实就是一个独立的访问路径,不同用户使用不同路径,各自有自己的队列、交换机,互相不会影响。
    在这里插入图片描述

加粗样式

  1. 绑定虚拟主机和用户
    创建好虚拟主机,我们还要给用户添加访问权限:
    点击添加好的虚拟主机,进入虚拟机设置界面:

在这里插入图片描述


4.RabbitMQ 的第一个程序

4.0 AMQP协议的回顾

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-78CbHYm7-1610726893687)(RibbitMQ 实战教程.assets/image-20200312140114784.png)]
虚拟主机对应数据库中的一个database!
使用时,新建虚拟主机,用户绑定虚拟主机!

4.1 RabbitMQ支持的消息模型

https://www.rabbitmq.com/getstarted.html

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

4.2 引入依赖

maven构建项目

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.7.2</version>
</dependency>

在网页上:

  • 新建虚拟主机 :/ems
  • 创建用户:ems, 权限为管理员
  • 用户绑定虚拟主机
    在这里插入图片描述

4.3 第一种模型(直连)

在这里插入图片描述
点对点
最简单的模型,只允许一个消费者消费,适用于登录,注册中调用发送短信等情况。

在上图的模型中,有以下概念:

  • P:生产者,也就是要发送消息的程序
  • C:消费者:消息的接受者,会一直等待消息到来。
  • queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。
1. 开发生产者
package helloword;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Zhao
 * @DATE 2021/1/16 - 23:58
 */
public class Provider {
    
    //生产消息
    @Test
    public void testSendMessage() throws IOException, TimeoutException {
        //创建链接mq的链接工厂对象
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置rabbitmq的主机
        connectionFactory.setHost("47.115.2.92");
        //设置端口号
        connectionFactory.setPort(5672);
        //设置连接那个虚拟主机
        connectionFactory.setVirtualHost("/ems");
        //设置访问虚拟主机的用户名和密码
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");

        //获取连接对象
        Connection connection = connectionFactory.newConnection();

        //获取连接中的通道
        Channel channel = connection.createChannel();

        //通道绑定对应消息队列
        //参数1:队列名称(队列不存在则直接创建)
        //参数2:定义队列是否持久化
        //参数3:exclusive 是否独占队列
        //参数4:autoDelete 是否在消息完成自动删除队列
        //参数5:额外附件参数
        channel.queueDeclare("hello",false,false,false,null);

        //发布消息
        //参数1:交换机名称 参数2:队列名称 参数3:传递消息额外设置 参数4:消息具体内容
        channel.basicPublish("","hello",null,"hello rabbitmq!".getBytes());


        channel.close();
        connection.close();
    }
}

在这里插入图片描述

2. 开发消费者
package helloword;

import com.rabbitmq.client.*;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Zhao
 * @DATE 2021/1/17 - 12:28
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("47.115.2.92");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/ems");
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");

        //创建连接对象
        Connection connection = connectionFactory.newConnection();

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

        //通道绑定对象 注意和消息发送端参数一致
        channel.queueDeclare("hello",false,false,false,null);

        //消费消息
        //参数1:消费哪个队列的消息 队列名称
        //参数2:开始消息的自动确认机制
        //参数3:消费时的回调接口

        channel.basicConsume("hello",true,new DefaultConsumer(channel){
            //最后一个参数:消息队列中区中的消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("new String(body) = " + new String(body));
            }
        });

        //不关闭资源,程序会一直运行,接受消息
//        channel.close();
//        connection.close();
    }
}

连接工具类封装

package utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 13:04
 */
public class RabbitMQUtils {
    private static ConnectionFactory connectionFactory;

    //类加载时就把工厂创建出来
    static {
        //重量级资源 类加载时执行,只执行一次
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("47.115.2.92");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/ems");
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");
    }

    //定义提供连接对象的方法
    public static Connection getConnection() {
        try {
            //重量级资源,可以在类加载时就把工厂创建出来
            //ConnectionFactory connectionFactory = new ConnectionFactory();
            /*connectionFactory.setHost("47.115.2.92");
            connectionFactory.setPort(5672);
            connectionFactory.setVirtualHost("/ems");
            connectionFactory.setUsername("ems");
            connectionFactory.setPassword("123");*/
            return connectionFactory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    //关闭通道和关闭连接工具方法
    public static void closeConnectionAndChannel(Channel channel, Connection connection) {
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以后直接调用工具类即可!

3. 参数的说明
  channel.queueDeclare("hello",true,false,false,null);
  '参数1':用来声明通道对应的队列,队列不存在则直接创建该队列
  '参数2':用来指定是否持久化队列
  '参数3':用来指定是否独占队列
  '参数4':用来指定消费完消息后是否自动删除队列
  '参数5':对队列的额外配置

注意:

  • 同一个通道可以向不同的队列发送消息

  • 队列持久化:
    在这里插入图片描述

  • 如果想让消息也持久化:
    发送消息时在参数3设置MessageProperties.PERSISTENT_TEXT_PLAIN

channel.basicPublish("","hello", MessageProperties.PERSISTENT_TEXT_PLAIN,"hello rabbitmq!".getBytes());
  • 发送参数和接收消息的持久化等参数要一致!不然会报错!
  • 独占队列
  • 消费完消息后是否自动删除队列
    必须在消费者断开连接后才会自动删除
    在这里插入图片描述

4.4 第二种模型(work quene)

第一种模式可能会导致消息堆积。
就需要多个消费者!
Work queues,也被称为(Task queues),任务模型。当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。此时就可以使用work 模型:让多个消费者绑定到一个队列,共同消费队列中的消息。队列中的消息一旦消费,就会消失,因此任务是不会被重复执行的。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Tu94k0rR-1610726893690)(RibbitMQ 实战教程.assets/image-20200314221002008.png)]

角色:

  • P:生产者:任务的发布者
  • C1:消费者-1,领取任务并且完成任务,假设完成速度较慢
  • C2:消费者-2:领取任务并完成任务,假设完成速度快

默认是平均分配消息的!

1. 开发生产者
package workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 13:57
 */
public class Provider {
    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        //获取通道对象
        Channel channel = connection.createChannel();

        //通过通道声明队列
        channel.queueDeclare("work",true,false,false,null);

        //生产消息
        for (int i = 0; i < 10; i++) {
            channel.basicPublish("","work",null,(i+"hello work queue!").getBytes());
        }

        //关闭资源
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);

    }
}

2.开发消费者-1
package workqueue;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author Zhao
 * @DATE 2021/1/17 - 14:02
 */
public class Consumer1 {
    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("work",true,false,false,null);

        channel.basicConsume("work",true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者-1:"+new String(body));
                //较慢,由于平均分配消息,因此会堆积消息
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
3.开发消费者-2
package workqueue;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;
import java.io.IOException;

/**
 * @author Zhao
 * @DATE 2021/1/17 - 14:02
 */
public class Consumer2 {
    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("work",true,false,false,null);

        channel.basicConsume("work",true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者-2:"+new String(body));
            }
        });
    }
}
4.测试结果

运行消费者1和消费者2,然后再运行生产者。
在这里插入图片描述

在这里插入图片描述

总结:默认情况下,RabbitMQ将按顺序将每个消息发送给下一个使用者。平均而言,每个消费者都会收到相同数量的消息。这种分发消息的方式称为循环。

5.消息自动确认机制

Doing a task can take a few seconds. You may wonder what happens if one of the consumers starts a long task and dies with it only partly done. With our current code, once RabbitMQ delivers a message to the consumer it immediately marks it for deletion. In this case, if you kill a worker we will lose the message it was just processing. We’ll also lose all the messages that were dispatched to this particular worker but were not yet handled.

But we don’t want to lose any tasks. If a worker dies, we’d like the task to be delivered to another worker.

//参数1:队列名称
//参数2:消息自动确认 true-消费者自动向rabbitmq确认消息消费 拿到了5个消息,消费到第三个时宕机了,剩下两个就丢失了;false-不会自动确认消息
channel.basicConsume("work",true, new DefaultConsumer(channel){
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        System.out.println("消费者-1:"+new String(body));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
         //手动确认 参数1:手动确认消息标识,确认队列中的哪个具体消息 参数2:是否开启多个消息同时确认 false 每次确认一个
        channel.basicAck(envelope.getDeliveryTag(),false);
    }
});
  • 设置通道一次只能消费一个消息
    消费者1
//设置每次只能消费1个消息
channel.basicQos(1);
  • 关闭消息的自动确认,开启手动确认消息
package workqueue;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 14:02
 */
public class Consumer1 {
    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        final Channel channel = connection.createChannel();
        //设置每次只能消费1个消息
        channel.basicQos(1);

        channel.queueDeclare("work",true,false,false,null);

        //参数1:队列名称
        //参数2:消息自动确认 true-消费者自动向rabbitmq确认消息消费 拿到了5个消息,消费到第三个时宕机了,剩下两个就丢失了;false-不会自动确认消息
        channel.basicConsume("work",false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者-1:"+new String(body));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                 //手动确认 参数1:手动确认消息标识,确认队列中的哪个具体消息 参数2:是否开启多个消息同时确认 false 每次确认一个
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

消费者2

package workqueue;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 14:02
 */
public class Consumer2 {
    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        final Channel channel = connection.createChannel();
        //设置每次只能消费1个消息
        channel.basicQos(1);

        channel.queueDeclare("work",true,false,false,null);

        channel.basicConsume("work",false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者-2:"+new String(body));
                //手动确认 参数1:手动确认消息标识,确认队列中的哪个具体消息 参数2:是否开启多个消息同时确认 false 每次确认一个
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

在这里插入图片描述
在这里插入图片描述

这样设置可以使消息消费者能者多劳,并且消费一条消息确认一条,避免消息丢失!


4.5 第三种模型(fanout)

fanout (扇出) 也称为广播

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wQtD5jSC-1610726893697)(RibbitMQ 实战教程.assets/image-20191126213115873.png)]

在广播模式下,消息发送流程是这样的:

  • 可以有多个消费者
  • 每个消费者有自己的queue(队列)
  • 每个队列都要绑定到Exchange(交换机)
  • 生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定。
  • 交换机把消息发送给绑定过的所有队列
  • 队列的消费者都能拿到消息。实现一条消息被多个消费者消费
1. 开发生产者
package fanout;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 17:40
 */
public class provider {
    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //将通道声明指定交换机
        //参数1:交换机名称 若不存在则直接创建
        //参数2:交换机类型 fanout-广播类型,一条消息多个消费者同时消费
        channel.exchangeDeclare("logs","fanout");

        //发布消息
        channel.basicPublish("logs","",null,"fanout type message".getBytes());

        //释放资源
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}

2. 开发消费者-1
package fanout;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 17:50
 */
public class Consumer1 {
    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //消费者貌似不需要绑定交换机
//        //通道绑定交换机
//        channel.exchangeDeclare("logs","fanout");

        //临时队列
        String queueName = channel.queueDeclare().getQueue();

        //绑定交换机和队列
        channel.queueBind(queueName,"logs","");

        //消费消息
        channel.basicConsume(queueName,true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1:"+new String(body));
            }
        });
    }
}
3. 开发消费者-2
package fanout;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 17:50
 */
public class Consumer2 {
    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //消费者不需要绑定交换机
//        //通道绑定交换机
//        channel.exchangeDeclare("logs","fanout");

        //临时队列
        String queueName = channel.queueDeclare().getQueue();

        //绑定交换机和队列
        channel.queueBind(queueName,"logs","");

        //消费消息
        channel.basicConsume(queueName,true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者2:"+new String(body));
            }
        });
    }
}

4.开发消费者-3
//绑定交换机
channel.exchangeDeclare("logs","fanout");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//将临时队列绑定exchange
channel.queueBind(queue,"logs","");
//处理消息
channel.basicConsume(queue,true,new DefaultConsumer(channel){
  @Override
  public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    System.out.println("消费者3: "+new String(body));
  }
});
5. 测试结果

三个消费者都能收到消息。


4.6 第四种模型(Routing)

4.6.1 Routing 之订阅模型-Direct(直连)

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

在Direct模型下:

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

流程:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3JFtdH8s-1610726893699)(RibbitMQ 实战教程.assets/image-20191126220145375.png)]
RoutingKey不同,消费者不同,这样可以实现有的需要持久化,有的不需要持久化等功能。

图解:

  • P:生产者,向Exchange发送消息,发送消息时,会指定一个routing key。
  • X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与routing key完全匹配的队列
  • C1:消费者,其所在队列指定了需要routing key 为 error 的消息
  • C2:消费者,其所在队列指定了需要routing key 为 info、error、warning 的消息
1. 开发生产者
package direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 18:25
 */
public class provider {
    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        //获取连接通道对象
        Channel channel = connection.createChannel();
        //通过通道声明交换机
        //参数1:交换机名称
        //参数2: direct 路由模式 交换机类型 基于指令的Routing key转发
        channel.exchangeDeclare("logs_direct", "direct");

        //发送消息
//        String routingKey = "info";
        String routingKey = "error";
        channel.basicPublish("logs_direct",routingKey,null,("这是direct模型发布的基于route key"+routingKey).getBytes());

        //关闭资源
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}

2.开发消费者-1
package direct;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 18:31
 */
public class Consumer1 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //通道声明交换机以及交换机的类型
        channel.exchangeDeclare("logs_direct", "direct");

        //创建一个临时队列
        String queueName = channel.queueDeclare().getQueue();

        //基于route key绑定队列和交换机
        channel.queueBind(queueName,"logs_direct","error");

        //获取消费的消息
        channel.basicConsume(queueName,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1:"+ new String(body));
            }
        });
    }
}

3.开发消费者-2
package direct;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 18:41
 */
public class Consumer2 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //声明交换机,以及交换机类型 direct
        channel.exchangeDeclare("logs_direct","direct");

        //创建临时队列
        String queueName = channel.queueDeclare().getQueue();

        //临时队列和交换机绑定
        channel.queueBind(queueName,"logs_direct","info");
        channel.queueBind(queueName,"logs_direct","error");
        channel.queueBind(queueName,"logs_direct","warning");

        //消费消息
        channel.basicConsume(queueName,true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者2:"+new String(body));
            }
        });
    }
}

4.测试生产者发送Route key为error和info的消息时

在这里插入图片描述
在这里插入图片描述
代码优化
String exchangeName = "logs_direct";

package direct;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 18:41
 */
public class Consumer2 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        String exchangeName = "logs_direct";

        //声明交换机,以及交换机类型 direct
        channel.exchangeDeclare(exchangeName,"direct");

        //创建临时队列
        String queueName = channel.queueDeclare().getQueue();

        //临时队列和交换机绑定
        channel.queueBind(queueName,exchangeName,"info");
        channel.queueBind(queueName,exchangeName,"error");
        channel.queueBind(queueName,exchangeName,"warning");

        //消费消息
        channel.basicConsume(queueName,true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者2:"+new String(body));
            }
        });
    }
}

注意:如果发送的消息没有被任何消费者绑定,则该消息不会被消费!


4.6.2 Routing 之订阅模型-Topic

Topic类型的ExchangeDirect相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符!这种模型Routingkey 一般都是由一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hrAn2wXa-1610726893708)(RibbitMQ 实战教程.assets/image-20191127121900255.png)]

  • 统配符
    * (star) can substitute for exactly one word. 匹配不多不少恰好1个词
    # (hash) can substitute for zero or more words. 匹配一个或多个词
  • 如:
    audit.# 匹配audit.irs.corporate或者 audit.irs 等
    audit.* 只能匹配 audit.irs
1.开发生产者
package topic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import utils.RabbitMQUtils;

import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 19:04
 */
public class provider {
    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //声明交换机以及交换机类型 topic 使用动态路由(通配符方式)
        channel.exchangeDeclare("tpoics", "topic");

        //发布消息
//        String routeKey = "user.save";
        String routeKey = "user.save.findAll";
        channel.basicPublish("topics",routeKey,null,("这里是topic动态路由模型,routeKey:"+routeKey).getBytes());

        //关闭资源
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}
2.开发消费者-1

Routing Key中使用*通配符方式
整体流程:获取连接,声明交换机,创建临时队列,绑定交换机和队列,消费消息

 //声明交换机
channel.exchangeDeclare("topics","topic");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//绑定队列与交换机并设置获取交换机中动态路由
channel.queueBind(queue,"topics","user.*");

//消费消息
channel.basicConsume(queue,true,new DefaultConsumer(channel){
  @Override
  public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    System.out.println("消费者1: "+new String(body));
  }
});
package topic;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;
import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 19:08
 */
public class Conusmer1 {
    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //声明交换机以及交换机类型
        channel.exchangeDeclare("topics", "topic");
        //创建一个临时队列
        String queueName = channel.queueDeclare().getQueue();
        //绑定队列和交换机 动态通配符形式 匹配 route key
        channel.queueBind(queueName, "topics", "user.*");
        //消费消息
        channel.basicConsume(queueName,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1:"+new String(body));
            }
        });


    }
}

3.开发消费者-2

Routing Key中使用#通配符方式

package topic;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;
import java.io.IOException;

/**
 * @author ZhaoZhiyue
 * @DATE 2021/1/17 - 19:08
 */
public class Conusmer2 {
    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //声明交换机以及交换机类型
        channel.exchangeDeclare("topics", "topic");
        //创建一个临时队列
        String queueName = channel.queueDeclare().getQueue();
        //绑定队列和交换机 动态通配符形式 匹配 route key
        channel.queueBind(queueName, "topics", "user.#");
        //消费消息
        channel.basicConsume(queueName,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1:"+new String(body));
            }
        });
    }
}

4.测试结果

在这里插入图片描述
在这里插入图片描述
剩下的两种模式:
RPC和发布订阅可以自己学习!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值