九点钟☆方向

记录成长点滴

欢迎来到我的个人博客~


RabbitMQ

目录

1.MQ引言

1.1 什么是MQ

MQ(Message Quene) : 翻译为 消息队列,通过典型的 生产者消费者模型,生产者不断向消息队列中生产消息,消费者不断的从队列中获取消息。因为消息的生产和消费都是异步的,而且只关心消息的发送和接收,没有业务逻辑的侵入,轻松的实现系统间解耦。别名为 消息中间件 通过利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成。

image-20220707125507477

1.2 MQ有哪些

当今市面上有很多主流的消息中间件,如老牌的ActiveMQRabbitMQ,炙手可热的Kafka,阿里巴巴自主开发RocketMQ等。

1.3 不同MQ特点

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

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

# 3.RocketMQ
	RocketMQ是阿里开源的消息中间件,它是纯Java开发,具有高吞吐量、高可用性、适合大规模分布式系统应用的特点。RocketMQ思路起源	  于Kafka,但并不是Kafka的一个Copy,它对消息的可靠传输及事务性做了优化,目前在阿里集团被广泛应用于交易、充值、流计算、消息推     送、日志流式处理、binglog分发等场景。开源版的rocketMQ已经交给Apache托管了,但是开源版并不支持分布式事务,只有购买官方版本     才会有,开源版功能会少点

# 4.RabbitMQ
	RabbitMQ是使用Erlang语言开发的开源消息队列系统,基于AMQP协议来实现。AMQP的主要特征是面向消息、队列、路由(包括点对点和发布/订阅)、可靠性、安全。AMQP协议更多用在企业系统内对数据一致性、稳定性和可靠性要求很高的场景,对性能和吞吐量的要求还在其次。可以与Spring无缝衔接
		

RabbitMQ比Kafka可靠,Kafka更适合IO高吞吐的处理,一般应用在大数据日志处理或对实时性(少量延迟),可靠性(少量丢数据)要求稍低的场景使用,比如ELK日志收集。


2.RabbitMQ 的引言

2.1 RabbitMQ

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

image-20190925215603036

官网: 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协议模型:

image-20200311182438041

2.2 RabbitMQ 的安装

2.2.1 下载

官网下载地址: https://www.rabbitmq.com/download.htmlimage-20190925220115235

最新版本: 3.7.18

2.2.2 下载的安装包image-20190925220343521

注意:这里的安装包是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

# 2.安装Erlang依赖包
	rpm -ivh erlang-22.0.7-1.el7.x86_64.rpm

# 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

# 5.查看配置文件位置
	ls /etc/rabbitmq/rabbitmq.config

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

image-20190925222230260

将上图中配置文件中红色部分去掉%%,以及最后的,逗号 修改为下图:

image-20190925222329200

# 7.执行如下命令,启动rabbitmq中的插件管理
	rabbitmq-plugins enable rabbitmq_management
	
	出现如下说明:
		Enabling plugins on node rabbit@localhost:
    rabbitmq_management
    The following plugins have been configured:
      rabbitmq_management
      rabbitmq_management_agent
      rabbitmq_web_dispatch
    Applying plugin configuration to rabbit@localhost...
    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.

# 8.启动RabbitMQ的服务
	systemctl start rabbitmq-server	启动
	systemctl restart rabbitmq-server	重启
	systemctl stop rabbitmq-server	关闭
	

# 9.查看服务状态(见下图:)
	systemctl status rabbitmq-server
  ● rabbitmq-server.service - RabbitMQ broker
     Loaded: loaded (/usr/lib/systemd/system/rabbitmq-server.service; disabled; vendor preset: disabled)
     Active: active (running) since 三 2019-09-25 22:26:35 CST; 7s ago
   Main PID: 2904 (beam.smp)
     Status: "Initialized"
     CGroup: /system.slice/rabbitmq-server.service
             ├─2904 /usr/lib64/erlang/erts-10.4.4/bin/beam.smp -W w -A 64 -MBas ageffcbf -MHas ageffcbf -
             MBlmbcs...
             ├─3220 erl_child_setup 32768
             ├─3243 inet_gethost 4
             └─3244 inet_gethost 4
      .........

image-20190925222743776

# 10.关闭防火墙服务
	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   

# 11.访问web管理界面
	http://10.15.0.8:15672/

image-20190926194738708

# 12.登录管理界面
	username:  guest
	password:  guest

image-20190926194954822


Rabbit在Ubuntu下安装最新版本

新建install.sh文件,内容如下

#!/usr/bin/sh
 
sudo apt-get install curl gnupg apt-transport-https -y
 
## Team RabbitMQ's main signing key
curl -1sLf "https://keys.openpgp.org/vks/v1/by-fingerprint/0A9AF2115F4687BD29803A206B73A36E6026DFCA" | sudo gpg --dearmor | sudo tee /usr/share/keyrings/com.rabbitmq.team.gpg > /dev/null
## Cloudsmith: modern Erlang repository
curl -1sLf https://dl.cloudsmith.io/public/rabbitmq/rabbitmq-erlang/gpg.E495BB49CC4BBE5B.key | sudo gpg --dearmor | sudo tee /usr/share/keyrings/io.cloudsmith.rabbitmq.E495BB49CC4BBE5B.gpg > /dev/null
## Cloudsmith: RabbitMQ repository
curl -1sLf https://dl.cloudsmith.io/public/rabbitmq/rabbitmq-server/gpg.9F4587F226208342.key | sudo gpg --dearmor | sudo tee /usr/share/keyrings/io.cloudsmith.rabbitmq.9F4587F226208342.gpg > /dev/null
 
## Add apt repositories maintained by Team RabbitMQ
sudo tee /etc/apt/sources.list.d/rabbitmq.list <<EOF
## Provides modern Erlang/OTP releases
##
deb [signed-by=/usr/share/keyrings/io.cloudsmith.rabbitmq.E495BB49CC4BBE5B.gpg] https://dl.cloudsmith.io/public/rabbitmq/rabbitmq-erlang/deb/ubuntu bionic main
deb-src [signed-by=/usr/share/keyrings/io.cloudsmith.rabbitmq.E495BB49CC4BBE5B.gpg] https://dl.cloudsmith.io/public/rabbitmq/rabbitmq-erlang/deb/ubuntu bionic main
 
## Provides RabbitMQ
##
deb [signed-by=/usr/share/keyrings/io.cloudsmith.rabbitmq.9F4587F226208342.gpg] https://dl.cloudsmith.io/public/rabbitmq/rabbitmq-server/deb/ubuntu bionic main
deb-src [signed-by=/usr/share/keyrings/io.cloudsmith.rabbitmq.9F4587F226208342.gpg] https://dl.cloudsmith.io/public/rabbitmq/rabbitmq-server/deb/ubuntu bionic main
EOF
 
## Update package indices
sudo apt-get update -y
 
## Install Erlang packages
sudo apt-get install -y erlang-base \
                        erlang-asn1 erlang-crypto erlang-eldap erlang-ftp erlang-inets \
                        erlang-mnesia erlang-os-mon erlang-parsetools erlang-public-key \
                        erlang-runtime-tools erlang-snmp erlang-ssl \
                        erlang-syntax-tools erlang-tftp erlang-tools erlang-xmerl
 
## Install rabbitmq-server and its dependencies
sudo apt-get install rabbitmq-server -y --fix-missing

执行文件

sudo ./install.sh
以上命令如果提示“找不到命令”,可以使用以下命令执行
sudo sh ./install.sh

测试是否安装成功

# 命令行输入 
erl

安装管理界面

sudo rabbitmq-plugins enable rabbitmq_management

管理页面安装成功测试访问

http://192.168.11.128:15672
新版本安装成功后,默认安装路径在user/lib/rabbitmq下
使用guest账号密码登录时会出现以下界面,这是因为rabbitmq从3.3.0开始禁止使用guest/guest权限通过除localhost外的访问,最好方式就新增一个账号

#第一步:添加 admin 用户并设置密码
rabbitmqctl add_user admin 123456
#第二步:添加 admin 用户为administrator角色
rabbitmqctl set_user_tags admin administrator
#第三步:设置 admin 用户的权限,指定允许访问的vhost以及write/read
rabbitmqctl set_permissions -p "/" admin ".*" ".*" ".*"
#第四步:查看vhost(/)允许哪些用户访问
rabbitmqctl list_permissions -p /
#第五步:查看用户列表
rabbitmqctl list_users
此时使用admin/123456就可以登录成功了

image-20220708220901701

常用命令

service rabbitmq-server   start
service rabbitmq-server   stop
service rabbitmq-server   status
service rabbitmq-server   rotate-logs
service rabbitmq-server   restart
service rabbitmq-server   condrestart
service rabbitmq-server   try-restart
service rabbitmq-server   reload
service rabbitmq-server   force-reload

3. RabiitMQ 配置

3.1RabbitMQ 管理命令行

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

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

# 3.插件管理命令行
	rabbitmq-plugins enable|list|disable 

3.2 web管理界面介绍

3.2.1 overview概览

image-20191126162026720

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

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

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

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

3.2.2 Admin用户和虚拟主机管理

1. 添加用户
image-20191126162617280

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

  • 超级管理员(administrator)

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

  • 监控者(monitoring)

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

  • 策略制定者(policymaker)

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

  • 普通管理者(management)

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

  • 其他

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

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

image-20191126163023153

3. 绑定虚拟主机和用户

创建好虚拟主机,我们还要给用户添加访问权限:

点击添加好的虚拟主机:

image-20191126163506795

进入虚拟机设置界面:

image-20191126163631889


4.RabbitMQ 的第一个程序

4.0 AMQP协议的回顾

image-20200312140114784

4.1 RabbitMQ支持的消息模型

image-20191126165434784

image-20191126165459282

4.2 引入依赖

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

4.3 第一种模型(直连)

image-20191126165840602

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

  • P:生产者,也就是要发送消息的程序
  • C:消费者:消息的接受者,会一直等待消息到来。
  • queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。
准备工作

先添加一个虚拟主机

image-20220708224039759

添加用户ems,密码为123

image-20220708224312686

image-20220708224257534

给新加的ems用户绑定虚拟主机

image-20220708224410193

image-20220708232338335

1. 开发生产者
public class Send {
    @Test
    public void testSend() throws IOException, TimeoutException { 
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //主机
        connectionFactory.setHost("10.15.0.9");
        //端口号,web管理界面的是15672,而Java链接通信的是5672
        connectionFactory.setPort(5672);
        //设置访问虚拟主机的用户名和密码
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");
        //设置连接那个虚拟主机
        connectionFactory.setVirtualHost("/ems");
        //获取连接对象
        Connection connection = connectionFactory.newConnection();
        //获取连接中的通道
        Channel channel = connection.createChannel();

        //通道绑定对应消息队列  
        //参数1: 队列名称,如果队列不存在会自动创建  
        //参数2: 是否持久化  
        //参数3 exclusive:是否独占队列 
        //参数4 autoDelete:是否在消费完成后自动删除队列
        //参数5:额外附加参数
        channel.queueDeclare("hello",true,false,false,null);
        //发布消息
        //参数1:交换机名称,这里是模型1没有交换机,为空
        //参数2:路由key,没有绑定时默认取队列名作为路由key
        //参数3:传递消息额外设置
        //参数4:消息的具体内容
        channel.basicPublish("","hello", null,"hello rabbitmq".getBytes());
        channel.close();
        connection.close();
}

image-20220708232656543

2. 开发消费者
//受限于Junit版本的问题,会出现消息消费后在回调函数打印之前主线程关闭,从而并未打印信息的情况,这里我们是使用main方法进行测试
public static void main(String[] args) throws IOException, TimeoutException {
    //创建连接工厂
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("10.15.0.9");
    connectionFactory.setPort(5672);
    connectionFactory.setUsername("ems");
    connectionFactory.setPassword("123");
    connectionFactory.setVirtualHost("/ems");
    //创建连接对象
    Connection connection = connectionFactory.newConnection();
    //创建通道
    Channel channel = connection.createChannel();
    //通道绑定消息队列
    channel.queueDeclare("hello", true, 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));
        }
    });
    //一般来说我们的消费者要一直监听消息队列,所以这里并不需要关闭
    //channel.close();
    //connection.close();
}

可以看到上面的生产者和消费者中存在着大量的代码重复,我们可以进行抽取

/**
* 抽取出重复代码到工具类中
*/
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class RabbitMQUtils {
    private static ConnectionFactory connectionFactory = null;
    static {
        //重量级资源 类加载时执行并且只执行一次
        connectionFactory =  new ConnectionFactory();
        connectionFactory.setHost("192.168.11.128");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/ems");
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");
    }

    //获取连接的方法
    public static Connection getConnection() {
        try{
            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();
        }
    }
}

/**
* 生产者中替换成工具类
*/
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Send {
    @Test
    public void testSend() throws IOException, TimeoutException {
//        ConnectionFactory connectionFactory = new ConnectionFactory();
//        connectionFactory.setHost("192.168.11.128");
//        connectionFactory.setPort(5672);
//        connectionFactory.setUsername("ems");
//        connectionFactory.setPassword("123");
//        connectionFactory.setVirtualHost("/ems");
//        Connection connection = connectionFactory.newConnection();
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("hello",true,false,false,null);
        channel.basicPublish("","hello",null,"hello rabbitmq".getBytes());
//        channel.close();
//        connection.close();
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}

/**
* 消费者中替换成工具类
*/
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

//消费者
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
//        ConnectionFactory connectionFactory = new ConnectionFactory();
//        connectionFactory.setHost("192.168.11.128");
//        connectionFactory.setPort(5672);
//        connectionFactory.setVirtualHost("/ems");
//        connectionFactory.setUsername("ems");
//        connectionFactory.setPassword("123");

//        Connection connection = connectionFactory.newConnection();
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("hello",true,false,false,null);
        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));
            }
        });
    }
}
3. 参数的说明
  channel.queueDeclare("hello",true,false,false,null);
  '参数1':用来声明通道对应的队列当队列不存在时会自动创建
  '参数2':用来指定是否持久化队列,如果为false,队列不会持久化重启rabbitmq后队列会消失注意这里只是队列持久化队列中的消息需要持久化的话需要通过下面语句进行设置
  '参数3':用来指定是否独占队列设置为true,只能被一个通道绑定其他通道在绑定时会报错
  '参数4':用来指定是否自动删除队列如果设置为true当队列中的消息被消费完并且队列与消费者完全断开后队列会自动删除注意如果消息消费完消费者还与队列保持连接的情况下是不会删除的比如这里我们的消费者代码中并未关闭连接所以不会消息我们将消费者的后台关闭后队列会消失
  '参数5':对队列的额外配置
      
  //消息进行持久化的设置,在发送消息时进行设置
  channel.basicPublish("","hello", MessageProperties.PERSISTENT_TEXT_PLAIN,"hello rabbitmq".getBytes());
 参数1交换机名称可以为空
 参数2路由key,没有绑定时默认取队列名作为路由key
 参数3传递消息额外设置通过这里设置消息进行持久化这样未消费的消息在重启rabbitmq后也会存在
 参数4消息的具体内容
     
 需要注意的是消息消费者要和生产者的队列保持一直
 比如之前生产者的队列设置了持久化队列为true这里第二个参数也要设置为true
 之前生产者设置了自动删除为true那这里第四个参数也要设置为true
 channel.queueDeclare("hello",true,false,false,null);    

image-20220709184339916

4.4 第二种模型(work quene)

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

image-20200314221002008

角色:

  • P:生产者:任务的发布者
  • C1:消费者-1,领取任务并且完成任务,假设完成速度较慢
  • C2:消费者-2:领取任务并完成任务,假设完成速度快
1. 开发生产者
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;

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);
        //生产20条消息
        for(int i=0;i<20;i++) {
            channel.basicPublish("","work",null,(i + "-hello work").getBytes());
        }
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}

2.开发消费者-1
mport com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

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));
            }
        });
    }
}
3.开发消费者-2
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

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.测试结果

image-20220709234625955

可以看到默认是平均消费的

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

但是在实际的开发中会存在有的消费者处理的快,有的消费者处理的慢的情况,如果还平均分配的话就会造成队列消息的积压,所以我们希望处理快的消费者多处理,能者多劳,可以通过确认机制完成

5.消息自动确认机制

之前我们的代码中设置了消息的自动确认

//第二个参数true代表自动确认
channel.basicConsume("hello",true,new DefaultConsumer(channel){……});

一旦开启了自动确认队列中的消息会一次性的发给消费者比如一次发送了5条消息消费者拿到后再消费了3条后宕机了那么剩下的2条则会丢失掉所以也会存在消息丢失的可能性

image-20220710132357260

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.

所以我们更新代码时需要从以下几个方面:

  • 设置通道一次只能消费一个消息

  • 关闭消息的自动确认,开启手动确认消息

更新以上代码

/**
* 生产者代码不变
*
*/
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);
        //生产20条消息
        for(int i=0;i<20;i++) {
            channel.basicPublish("","work",null,(i + "-hello work").getBytes());
        }
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}



/**
* 消费者1
*channel.basicQos(1);	每次只发一条
*channel.basicConsume("work",false,new DefaultConsumer(channel){})	关闭自动确认
*channel.basicAck(envelope.getDeliveryTag(),false);	手动确认
*/
public class Consumer1 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare("work",true,false,false,null);
        //告诉消息队列不要全部发送,每次只能消费一个消息,剩余的仍在消息队列中保存,避免消息丢失
        channel.basicQos(1);
//        channel.basicConsume("work",true,new DefaultConsumer(channel){
        //关闭自动分配
        channel.basicConsume("work",false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //为了体现出消费者1和2处理效率的不同,这里让消费者1每次睡1秒
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者1:" + new String(body));
                //手动确认消息
                //参数1:消息标识,用于确认队列中的具体那个消息  参数2:是否开启多个消息同时确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

/**
* 消费者2 和消费者1一样的设置
*channel.basicQos(1);	每次只发一条
*channel.basicConsume("work",false,new DefaultConsumer(channel){})	关闭自动确认
*channel.basicAck(envelope.getDeliveryTag(),false);	手动确认
*/
public class Consumer2 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare("work",true,false,false,null);
        //每次只消费1个消息
        channel.basicQos(1);
//        channel.basicConsume("work",true,new DefaultConsumer(channel){
        //关闭消息自动确认
        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));
                //开启自动确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}


通过执行可以看到消费者1因为消费的慢只消费了1条消息而消费者2消费了19条

image-20220710135101496


4.5 第三种模型(fanout)

前两种模式也并不是说没用到交换机exchange,而是使用了系统默认的,在第三种模型中,我们将使用自定义的交换机

fanout 扇出 也称为广播

image-20191126213115873

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

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

import java.io.IOException;

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", BuiltinExchangeType.FANOUT);
        //channel.exchangeDeclare("logs",“fanout");这种写法也可以
        //发布消息
        channel.basicPublish("logs","",null,"hello fanout message".getBytes());
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}

2. 开发消费者-1
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

public class Consumer1 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        //通道绑定交换机
        channel.exchangeDeclare("logs", BuiltinExchangeType.FANOUT);
        //生成临时队列
        String queue = channel.queueDeclare().getQueue();
        //绑定交换机和队列
        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("消费者1:" + new String(body));
            }
        });
    }
}

3. 开发消费者-2
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

public class Consumer2 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        //通道绑定交换机
        channel.exchangeDeclare("logs", BuiltinExchangeType.FANOUT);
        //生成临时队列
        String queue = channel.queueDeclare().getQueue();
        //绑定交换机和队列
        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("消费者2:" + new String(body));
            }
        });
    }
}

4.开发消费者-3
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

public class Consumer3 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        //通道绑定交换机
        channel.exchangeDeclare("logs", BuiltinExchangeType.FANOUT);
        //生成临时队列
        String queue = channel.queueDeclare().getQueue();
        //绑定交换机和队列
        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. 测试结果

新建的exchange

image-20220710165810098

运行消费者1、2、3后,启动生产者发送消息后,会发现3个消费者全部都收到了消息

image-20220710170047165


4.6 第四种模型(Routing)

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

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

在Direct模型下:

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

流程:

image-20191126220145375

图解:

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

public class Provider {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("logs_direct", BuiltinExchangeType.DIRECT);
       	//routingKey
        String key = "info";
        channel.basicPublish("logs_direct",key,null,("指定的route key 为"+key+" 的消息").getBytes());
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}

2.开发消费者-1
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

public class Consumer1 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("logs_direct", BuiltinExchangeType.DIRECT);
        String queue = channel.queueDeclare().getQueue();
        //通过指定routingKey为info,只接收对应routingKey相同的信息
        channel.queueBind(queue,"logs_direct","info");
        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));
            }
        });
    }
}

3.开发消费者-2
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

public class Consumer2 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("logs_direct", BuiltinExchangeType.DIRECT);
        String queue = channel.queueDeclare().getQueue();
        //可以绑定多个,这里可以接收routingKey为error、info、warn的信息
        channel.queueBind(queue,"logs_direct","error");
        channel.queueBind(queue,"logs_direct","info");
        channel.queueBind(queue,"logs_direct","warn");
        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("消费者2:"+ new String(body));
            }
        });
    }
}

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

只有消费者2可以接收到

image-20220710175807450

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

两个消费者都可以接收到

image-20220710175930042


4.6.2 Routing 之订阅模型-Topic

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

image-20191127121900255

# 统配符
	* (star) can substitute for exactly one word.    匹配1个词
	# (hash) can substitute for zero or more words.  匹配零个或多个词
# 如:
	audit.#   匹配audit.irs.corporate或者 audit.irs或者audit等
    audit.*   只能匹配 audit.irs
1.开发生产者
import com.mg.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;

public class Provider {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("topics", BuiltinExchangeType.TOPIC);
        String routekey = "user.save";
        channel.basicPublish("topics",routekey,null,("这是路由中的动态订阅模型,route key: ["+routekey+"]").getBytes());
        RabbitMQUtils.closeConnectionAndChannel(channel,connection);
    }
}

2.开发消费者-1

Routing Key中使用*通配符方式

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

public class Consumer1 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("topics", BuiltinExchangeType.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));
            }
        });
    }
}

3.开发消费者-2

Routing Key中使用#通配符方式

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

public class Consumer2 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("topics", BuiltinExchangeType.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("消费者2: "+new String(body));
            }
        });
    }
}

4.测试结果

可以看到都能匹配上,所以都能接收到消息image-20200316113935785

image-20200316114000459

5. SpringBoot中使用RabbitMQ

5.0 搭建初始环境

1. 引入依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 配置配置文件
spring:
  application:
    name: springboot_rabbitmq
  rabbitmq:
    host: 10.15.0.9
    port: 5672
    username: ems
    password: 123
    virtual-host: /ems

RabbitTemplate 用来简化操作 使用时候直接在项目中注入即可使用

5.1 第一种hello world模型使用

  1. 开发生产者
    import com.mg.rabbit_springboot.RabbitSpringbootApplication;
    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;
       
    @SpringBootTest(classes = RabbitSpringbootApplication.class)
    @RunWith(SpringRunner.class)
    public class Provider {
        @Autowired
        private RabbitTemplate rabbitTemplate;
       
        @Test
        public void testHelloWord() {
            //参数1:routingKey,如果不指定的话默认会把队列名作为routingKey
            //参数2:发送的内容,springboot这里可以发送一个对象
            rabbitTemplate.convertAndSend("hello","hello world模型");
        }
    }
       
    
  2. 开发消费者
    import org.springframework.amqp.rabbit.annotation.Queue;
    import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Component;
       
    @Component
    @RabbitListener(queuesToDeclare = @Queue("hello"))
    //同时也可以设置像持久化、自动删除等属性
    //@RabbitListener(queuesToDeclare = @Queue(value = "hello",durable = "true",autoDelete = "true"))
    public class HelloConsumer {
        @RabbitHandler
        //方法名称随便取
        public void receive(String message){
            System.out.println("接收的消息为:" + message);
        }
    }
       
    

5.2 第二种work模型使用

  1. 开发生产者
    @SpringBootTest(classes = RabbitSpringbootApplication.class)
    @RunWith(SpringRunner.class)
    public class Provider {
        @Autowired
        private RabbitTemplate rabbitTemplate;
           
        @Test
        public void testWork() {
            //发送10条消息
            for (int i = 0; i < 10; i++) {
                rabbitTemplate.convertAndSend("work","work模型发送的消息:"+i);
            }
        }
    }
       
    
  2. 开发消费者
    @Component
    public class WorkConsumer {
        @RabbitListener(queuesToDeclare = @Queue(value = "work"))
        public void workConsumer1(String message) {
            System.out.println("消费者1:"+message);
        }
       
        @RabbitListener(queuesToDeclare = @Queue(value = "work"))
        public void workConsumer2(String message) {
            System.out.println("消费者2:"+message);
        }
    }
    

    说明:默认在Spring AMQP实现中Work这种方式就是公平调度,如果需要实现能者多劳需要额外配置

5.3 Fanout 广播模型

  1. 开发生产者
    @SpringBootTest(classes = RabbitSpringbootApplication.class)
    @RunWith(SpringRunner.class)
    public class Provider {
        @Autowired
        private RabbitTemplate rabbitTemplate;
       
        @Test
        public void testFanout() {
            rabbitTemplate.convertAndSend("logs","","fanout广播类型发送的消息");
        }
    }
       
    
  2. 开发消费者
    @Component
    public class FanoutConsumer {
       
        @RabbitListener(bindings = {
                @QueueBinding(
                        value = @Queue, //创建临时对列
                        exchange = @Exchange(value = "logs",type = "fanout")    //绑定交换机
                )
        })
        public void fanoutConsumer1(String message) {
            System.out.println("广播消费者1:"+message);
        }
       
        @RabbitListener(bindings = {
                @QueueBinding(
                        value = @Queue,
                        exchange = @Exchange(value = "logs",type = "fanout")
                )
        })
        public void fanoutConsumer2(String message) {
            System.out.println("广播消费者2:"+message);
        }
    }
    

5.4 Route 路由模型

  1. 开发生产者
    @SpringBootTest(classes = RabbitSpringbootApplication.class)
    @RunWith(SpringRunner.class)
    public class Provider {
        @Autowired
        private RabbitTemplate rabbitTemplate;
       
        @Test
        public void testRoute() {
            rabbitTemplate.convertAndSend("route_direct","error","route模式发送的error消息");
        }
    }
       
    
  2. 开发消费者
    @Component
    public class RouteConsumer {
        @RabbitListener(bindings = @QueueBinding(
                value = @Queue,
                exchange = @Exchange(value = "route_direct",type = "direct"),
                key = {"info"} //指定接收那些路由key
        ))
        public void routeConsumer1(String message) {
            System.out.println("routeConsumer1:"+message);
        }
       
        @RabbitListener(bindings = @QueueBinding(
                value = @Queue,
                exchange = @Exchange(value = "route_direct",type = "direct"),
                key = {"error","warn","info"}   //指定接收那些路由key
        ))
        public void routeConsumer2(String message) {
            System.out.println("routeConsumer2:"+message);
        }
    }
       
    

5.5 Topic 订阅模型(动态路由模型)

  1. 开发生产者
    @SpringBootTest(classes = RabbitSpringbootApplication.class)
    @RunWith(SpringRunner.class)
    public class Provider {
        @Autowired
        private RabbitTemplate rabbitTemplate;
           
        @Test
        public void testTopic() {
            rabbitTemplate.convertAndSend("topics","user.save.findAll","topic动态路由发送的消息");
        }
    }
       
    
  2. 开发消费者
    @Component
    public class TopicConsumer {
       
        @RabbitListener(bindings = @QueueBinding(
                value = @Queue,
                exchange = @Exchange(value = "topics",type = "topic"),
                key = {"user.*"}
        ))
        public void topicConsumer1(String message) {
            System.out.println("topic消费者1:"+message);
        }
       
        @RabbitListener(bindings = @QueueBinding(
                value = @Queue,
                exchange = @Exchange(value = "topics",type = "topic"),
                key = {"user.#"}
        ))
        public void topicConsumer2(String message) {
            System.out.println("topic消费者2:"+message);
        }
    }
       
    

6. MQ的应用场景

6.1 异步处理

场景说明:用户注册后,需要发注册邮件和注册短信,传统的做法有两种 1.串行的方式 2.并行的方式

  • 串行方式: 将注册信息写入数据库后,发送注册邮件,再发送注册短信,以上三个任务全部完成后才返回给客户端。 这有一个问题是,邮件,短信并不是必须的,它只是一个通知,而这种做法让客户端等待没有必要等待的东西.

这里写图片描述

  • 并行方式: 将注册信息写入数据库后,发送邮件的同时,发送短信,以上三个任务完成后,返回给客户端,并行的方式能提高处理的时间。

这里写图片描述

  • 消息队列:假设三个业务节点分别使用50ms,串行方式使用时间150ms,并行使用时间100ms。虽然并行已经提高的处理时间,但是,前面说过,邮件和短信对我正常的使用网站没有任何影响,客户端没有必要等着其发送完成才显示注册成功,应该是写入数据库后就返回. 消息队列: 引入消息队列后,把发送邮件,短信不是必须的业务逻辑异步处理

    img

由此可以看出,引入消息队列后,用户的响应时间就等于写入数据库的时间+写入消息队列的时间(可以忽略不计),引入消息队列后处理后,响应时间是串行的3倍,是并行的2倍。

6.2 应用解耦

场景:双11是购物狂节,用户下单后,订单系统需要通知库存系统,传统的做法就是订单系统调用库存系统的接口.

这里写图片描述

这种做法有一个缺点:

当库存系统出现故障时,订单就会失败。 订单系统和库存系统高耦合. 引入消息队列

这里写图片描述

  • 订单系统:用户下单后,订单系统完成持久化处理,将消息写入消息队列,返回用户订单下单成功。

  • 库存系统:订阅下单的消息,获取下单消息,进行库操作。 就算库存系统出现故障,消息队列也能保证消息的可靠投递,不会导致消息丢失.

6.3 流量削峰

场景: 秒杀活动,一般会因为流量过大,导致应用挂掉,为了解决这个问题,一般在应用前端加入消息队列。

作用:

​ 1.可以控制活动人数,超过此一定阀值的订单直接丢弃(我为什么秒杀一次都没有成功过呢^^)

​ 2.可以缓解短时间的高流量压垮应用(应用程序按自己的最大处理能力获取订单)

这里写图片描述

1.用户的请求,服务器收到之后,首先写入消息队列,加入消息队列长度超过最大值,则直接抛弃用户请求或跳转到错误页面.

2.秒杀业务根据消息队列中的请求信息,再做后续处理.


7. RabbitMQ的集群

7.1 集群架构

7.1.1 普通集群(副本集群)

All data/state required for the operation of a RabbitMQ broker is replicated across all nodes. An exception to this are message queues, which by default reside on one node, though they are visible and reachable from all nodes. To replicate queues across nodes in a cluster –摘自官网

默认情况下:RabbitMQ代理操作所需的所有数据/状态都将跨所有节点复制。这方面的一个例外是消息队列,默认情况下,消息队列位于一个节点上,尽管它们可以从所有节点看到和访问

  1. 架构图

image-20200320094147471

​ 核心解决问题: 当集群中某一时刻master节点宕机,可以对Quene中信息,进行备份

  1. 集群搭建
    # 0.集群规划
    	node1: 10.15.0.3  mq1  master 主节点
    	node2: 10.15.0.4  mq2  repl1  副本节点
    	node3: 10.15.0.5  mq3  repl2  副本节点
       
    # 1.克隆三台机器主机名和ip映射
    	vim /etc/hosts加入:
    		 10.15.0.3 mq1
        	10.15.0.4 mq2
        	10.15.0.5 mq3
    	node1: vim /etc/hostname 加入:  mq1
    	node2: vim /etc/hostname 加入:  mq2
    	node3: vim /etc/hostname 加入:  mq3
       
    # 2.三个机器安装rabbitmq,并同步cookie文件,在node1上执行:
    	scp /var/lib/rabbitmq/.erlang.cookie root@mq2:/var/lib/rabbitmq/
    	scp /var/lib/rabbitmq/.erlang.cookie root@mq3:/var/lib/rabbitmq/
       
    # 3.查看cookie是否一致:
    	node1: cat /var/lib/rabbitmq/.erlang.cookie 
    	node2: cat /var/lib/rabbitmq/.erlang.cookie 
    	node3: cat /var/lib/rabbitmq/.erlang.cookie 
       
    # 4.后台启动rabbitmq所有节点执行如下命令,启动成功访问管理界面:
    	rabbitmq-server -detached 
       
    # 5.在node2和node3执行加入集群命令:
    	1.关闭       rabbitmqctl stop_app
    	2.加入集群    rabbitmqctl join_cluster rabbit@mq1
    	3.启动服务    rabbitmqctl start_app
       
    # 6.查看集群状态,任意节点执行:
    	rabbitmqctl cluster_status
       
    # 7.如果出现如下显示,集群搭建成功:
    	Cluster status of node rabbit@mq3 ...
    	[{nodes,[{disc,[rabbit@mq1,rabbit@mq2,rabbit@mq3]}]},
    	{running_nodes,[rabbit@mq1,rabbit@mq2,rabbit@mq3]},
    	{cluster_name,<<"rabbit@mq1">>},
    	{partitions,[]},
    	{alarms,[{rabbit@mq1,[]},{rabbit@mq2,[]},{rabbit@mq3,[]}]}]
       
    # 8.登录管理界面,展示如下状态:
    

    image-20200320095613586

    # 9.测试集群在node1上,创建队列
    

    image-20200320095743935

    # 10.查看node2和node3节点:
    

    image-20200320095827688

    image-20200320095843370

    # 11.关闭node1节点,执行如下命令,查看node2和node3:
    	rabbitmqctl stop_app
    

    image-20200320100000347

    image-20200320100010968


7.1.2 镜像集群

This guide covers mirroring (queue contents replication) of classic queues –摘自官网

By default, contents of a queue within a RabbitMQ cluster are located on a single node (the node on which the queue was declared). This is in contrast to exchanges and bindings, which can always be considered to be on all nodes. Queues can optionally be made mirrored across multiple nodes. –摘自官网

镜像队列机制就是将队列在三个节点之间设置主从关系,消息会在三个节点之间进行自动同步,且如果其中一个节点不可用,并不会导致消息丢失或服务不可用的情况,提升MQ集群的整体高可用性。

  1. 集群架构图

    image-20200320113423235

  2. 配置集群架构
    # 0.策略说明
    	rabbitmqctl set_policy [-p <vhost>] [--priority <priority>] [--apply-to <apply-to>] <name> <pattern>  <definition>
    	-p Vhost: 可选参数,针对指定vhost下的queue进行设置
    	Name:     policy的名称
    	Pattern: queue的匹配模式(正则表达式)
    	Definition:镜像定义,包括三个部分ha-mode, ha-params, ha-sync-mode
               		ha-mode:指明镜像队列的模式,有效值为 all/exactly/nodes
                            all:表示在集群中所有的节点上进行镜像
                            exactly:表示在指定个数的节点上进行镜像,节点的个数由ha-params指定
                            nodes:表示在指定的节点上进行镜像,节点名称通过ha-params指定
                	 ha-params:ha-mode模式需要用到的参数
                    ha-sync-mode:进行队列中消息的同步方式,有效值为automatic和manual
                    priority:可选参数,policy的优先级
                       
                        
    # 1.查看当前策略
    	rabbitmqctl list_policies
       
    # 2.添加策略
    	rabbitmqctl set_policy ha-all '^hello' '{"ha-mode":"all","ha-sync-mode":"automatic"}' 
    	说明:策略正则表达式为 “^” 表示所有匹配所有队列名称  ^hello:匹配hello开头队列
       
    # 3.删除策略
    	rabbitmqctl clear_policy ha-all
       
    # 4.测试集群
    

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦