RabbitMQ

  • 1:引言
  • 2:安装
    • 2-1:下载并安装erlang
    • 2-2:下载并安装RabbitMQ
  • 3:Rabbitmq的demo
  • 4:Rabbitmq的模型
    • 4-1:"Hello World!"模型:简单生产者-消费者
    • 4-2:Work queues模型:工作队列
    • 4-3:Publish/Subscribe模型:发布订阅模式,广播模型
    • 4-4:Routing模型:路由模型,订阅模式Direct
    • 4-5:Topics模型:动态路由模型,订阅模式Topics
  • 5:springBoot整合Rabbitmq
    • 5-1:"Hello World!"模型:简单生产者-消费者
    • 5-2:Work queues模型:工作队列
    • 5-3:Publish/Subscribe模型:发布订阅模式,广播模型
    • 5-4:Routing模型:路由模型,订阅模式Direct
    • 5-5:Topics模型:动态路由模型,订阅模式Topics

 

1:引言

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

2:安装

      RabbitMQ是基于AMQP协议,erlang语言开发,是部署最广泛免得开源消息中间件,是最受欢迎的开源消息中间件之一,其官网地址为https://www.rabbitmq.com/,所以要安装RabbitMQ之前,需要先安装erlang

2-1:下载并安装erlang

      下载地址:http://www.erlang.org/downloads
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot
      根据本机位数选择erlang下载版本
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_使用_02
      双击,点next就可以安装
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_03
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_04
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot_05
      安装完事后要记得配置一下系统的环境变量:此电脑–>鼠标右键“属性”–>高级系统设置–>环境变量–>“新建”系统环境变量
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_06

  • 变量名:ERLANG_HOME
  • 变量值就是刚才erlang的安装地址,点击确定。

      然后双击系统变量path,将%ERLANG_HOME%\bin加入到path中。
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_07
      最后windows键+R键,输入cmd,再输入erl,看到版本号就说明erlang安装成功了。如下图
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_08

2-2:下载并安装RabbitMQ

      下载地址:http://www.rabbitmq.com/download.html
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_使用_09
      点击下载,我下载的是3.8.12版本
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_10
      双击下载后的.exe文件,安装过程与erlang的安装过程相同
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_11
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_12
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_13
      安装完后的样子
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_14
      安装完事后要记得配置一下系统的环境变量:此电脑–>鼠标右键“属性”–>高级系统设置–>环境变量–>“新建”系统环境变量
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_15

  • 变量名:RABBITMQ_SERVER
  • 变量值就是刚才RabbitMQ的安装地址,点击确定。

      然后双击系统变量path,将%RABBITMQ_SERVER%\bin加入到path中。
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot_16
      cmd中输入(因为我的安装目录是D:\Software\Development\RabbitMQ\rabbitmq_server-3.8.12)

"D:\Software\Development\RabbitMQ\rabbitmq_server-3.8.12\sbin\rabbitmq-plugins.bat" enable rabbitmq_management

RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_使用_17

  • 启动RabbitMQ:net start RabbitMQ
  • 关闭RabbitMQ:net stop RabbitMQ
  • 访问管理界面:http://localhost:15672/
  • 默认用户名:guest
  • 默认密码为:guest
    RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_18

默认配置文件:

  • C:\Users\你的用户名\AppData\Roaming\RabbitMQ\advanced.config

数据目录:

  • C:\Users\用户名\AppData\Roaming\RabbitMQ\db\rabbit@用户名-mnesia

      附:

      如果遇到无法启动的问题,先尝试在控制面板 —— 服务 —— 中启动。如果已经启动了,先服务里面停掉或者尝试用命令

.\rabbitmq-server.bat start

      注意只能用CMD,不要用powershell

      如果要初始化RabbitMQ,移除全部数据:

  • 1、rabbitmq-service remove
  • 2、rabbitmq-service install
  • 3、rabbitmq-service start
3:Rabbitmq的demo

      写demo之前,我们先建立虚拟主机
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_19
      然后建立账户
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot_20
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_使用_21
      给账户设置虚拟主机的权限
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot_22
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_23

RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_24
      需要依赖包

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

      为了方便,我们直接封装连接RabbitMQ的工具类RabbitMQUtils

package com.lingaolu.utils;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;

public class RabbitMQUtils {

    private static ConnectionFactory connectionFactory;
    static {
        connectionFactory = new ConnectionFactory();
        // MQ服务的IP地址
        connectionFactory.setHost("127.0.0.1");
        // MQ服务的端口号
        connectionFactory.setPort(5672);
        // 虚拟主机的名称
        connectionFactory.setVirtualHost("/test");
        // 用户名
        connectionFactory.setUsername("test");
        // 密码
        connectionFactory.setPassword("123");
    }
    // 定义提供链接对象的方法
    public static Connection getConnection(){
        try {
            return connectionFactory.newConnection();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 定义获得通道的工具方法
    public static Channel getChannel(Connection connection){
        if(null != connection){
            try {
                return connection.createChannel();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    // 关闭通道和关闭连接工具方法
    public static void closeChannelAndConnection(Channel channel,Connection connection){
        try {
            if(null != channel){
                channel.close();
            }
            if(null != connection){
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

      生产者

@Test
void sentMessage() throws IOException {
    Connection connection = RabbitMQUtils.getConnection();
    Channel channel = RabbitMQUtils.getChannel(connection);
    if(null != channel){
        /**
         * 绑定对象方法
         * 参数1:队列名称,如果队列不存在自动创建
         * 参数2:用来定义队列特性是否要持久化,true代表持久化队列,false代表不持久化
         * 参数3:exclusive:是否独占队列 ,true代表独占队列,false代表不独占队列
         * 参数4:autoDelete:是否在消费完成后自动删除队列,true代表自动删除,即当队列中没有任何消息后,是否自动删除
         * 参数5:额外附加参数
         */
        channel.queueDeclare("hello",true,false,false,null);
        /**
         * 参数1:交换机名称
         * 参数2:路由规则,只要你的路由规则与这个交换机中有同名的队列,他就会自动路由上
         * 参数3:传递消息而外设置,MessageProperties.PERSISTENT_TEXT_PLAIN表示消息持久化,null表示不持久化
         * 参数4:消息的具体内容
         */
        channel.basicPublish("","hello",MessageProperties.PERSISTENT_TEXT_PLAIN,"消息内容".getBytes());
    }
    RabbitMQUtils.closeChannelAndConnection(channel,connection);
}

      消费者

@Test
void customer() throws IOException {
    Connection connection = RabbitMQUtils.getConnection();
    Channel channel = RabbitMQUtils.getChannel(connection);
    if(null != channel){
        // 绑定对象方法,消费者绑定的参数要与生产者绑定的参数严格一致,比如是否持久化,独占队列,删除等等
        channel.queueDeclare("hello",true,false,false,null);
        /**
         * 消费消息
         * 参数1:消费哪个队列的消息,队列名称
         * 参数2:开始消息的自动确认机制,true消费者自动向rabbitmq确认消息消费,false不会自动确认消息,需要手动确认
         * 参数3:消费时的回调接口
         */
        channel.basicConsume("hello",true,new DefaultConsumer(channel){
            // 最后一个参数:消息队列中取出的消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body){
                System.out.println("======================"+new String(body));
            }
        });
    }
}
4:Rabbitmq的模型

      Rabbitmq提供了很多模型,如下图所示

  • "Hello World!"模型:简单生产者-消费者
  • Work queues模型:工作队列
  • Publish/Subscribe模型:发布订阅模式,广播模型
  • Routing模型:路由模型,订阅模式Direct
  • Topics模型:动态路由模型,订阅模式Topics
  • RPC模型
  • Publisher Confirms模型

RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_25
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_26
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_27

4-1:"Hello World!"模型:简单生产者-消费者

RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_28

      我们在第二章的Rabbitmq的demo使用的就是"Hello World!"模型,所以这里不再举例

4-2:Work queues模型:工作队列

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

@Test
void sentMessage() throws IOException {
    Connection connection = RabbitMQUtils.getConnection();
    Channel channel = RabbitMQUtils.getChannel(connection);
    if(null != channel){
        channel.queueDeclare("work",true,false,false,null);
        for (int i = 1; i <=10 ; i++) {
            channel.basicPublish("","work",MessageProperties.PERSISTENT_TEXT_PLAIN,("消息内容"+i).getBytes());
        }
    }
    RabbitMQUtils.closeChannelAndConnection(channel,connection);
}

平均消费模式

      消费者1

package com.lingaolu;

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

public class customer1 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            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){
                    System.out.println("消费者1=============="+new String(body));
                }
            });
        }
    }
}

      消费者2

package com.lingaolu;

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

public class customer2 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            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){
                    System.out.println("消费者2=============="+new String(body));
                }
            });
        }
    }
}

      运行消费者1和消费者2,接着运行生产者,发现消费者1和消费者2是平均消费队列里的消息
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_30
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_31

确认机制和能者多劳消费模式

      消费者1

package com.lingaolu;

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

public class customer1 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 每次消费一个消息
            channel.basicQos(1);
            channel.queueDeclare("work",true,false,false,null);
            // 第二个参数false,手动确认消费消息,防止消息一下子都进入消费者
            channel.basicConsume("work",false,new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    // 加一个睡眠,模拟消费者1消费慢
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("消费者1=============="+new String(body));
                    // 确认消息消费,参数1:确认队列中哪个具体消息,参数2:是否开启多个消息同时确认
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            });
        }
    }
}

      消费者2

package com.lingaolu;

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

public class customer2 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 每次消费一个消息
            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:是否开启多个消息同时确认
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            });
        }
    }
}

      运行消费者1和消费者2,接着运行生产者,发现由于消费者1睡眠耗时,而消费者2消费的比较快,所以消费者2消费的消息比较多,实现能者多劳
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_32
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_33

4-3:Publish/Subscribe模型:发布订阅模式,广播模型

      fanout 扇出,也称为广播
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_使用_34

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

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

      生产者

@Test
void sentMessage() throws IOException {
    Connection connection = RabbitMQUtils.getConnection();
    Channel channel = RabbitMQUtils.getChannel(connection);
    if(null != channel){
        /**
         * 将通道声明指定为交换机
         * 参数1:交换机名称,不存在会自动创建
         * 参数2:交换机类型,fanout:广播类型
         */
        channel.exchangeDeclare("myExchange",BuiltinExchangeType.FANOUT);
        // 向交换机发送消息
        channel.basicPublish("myExchange","",MessageProperties.PERSISTENT_TEXT_PLAIN,"消息内容".getBytes());
    }
    RabbitMQUtils.closeChannelAndConnection(channel,connection);
}

      消费者1

package com.lingaolu;

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

public class customer1 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 临时队列
            String queueName = channel.queueDeclare().getQueue();
            // 绑定交换机和队列
            channel.queueBind(queueName,"myExchange","");
            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));
                }
            });
        }
    }
}

      消费者2

package com.lingaolu;

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

public class customer2 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 临时队列
            String queueName = channel.queueDeclare().getQueue();
            // 绑定交换机和队列
            channel.queueBind(queueName,"myExchange","");
            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));
                }
            });
        }
    }
}

      运行消费者1和消费者2,接着运行生产者,发现消费者1和消费者2都能同时消费生产者生产的消息,实现一个消息多个消费者消费的目的
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_35
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot_36

4-4:Routing模型:路由模型,订阅模式Direct

      在fanout广播模式中,一条消息,会被所有订阅的队列都消费,但是,在某些场景下,我们希望不同的消息被不同的队列消费,这时就要用到Direct类型的交换机Exchange
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_37

在Direct模型下

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

      生产者,路由key为info

@Test
void sentMessage() throws IOException {
    Connection connection = RabbitMQUtils.getConnection();
    Channel channel = RabbitMQUtils.getChannel(connection);
    if(null != channel){
        /**
         * 将通道声明指定为交换机
         * 参数1:交换机名称,不存在会自动创建
         * 参数2:交换机类型,direct:路由模式
         */
        channel.exchangeDeclare("mylog",BuiltinExchangeType.DIRECT);
        // 路由key
        String routingKey = "info";
        // 向交换机发送消息
        channel.basicPublish("mylog",routingKey,null,("消息内容"+routingKey).getBytes());
    }
    RabbitMQUtils.closeChannelAndConnection(channel,connection);
}

      消费者1,绑定路由key为info

package com.lingaolu;

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

public class customer1 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 临时队列
            String queueName = channel.queueDeclare().getQueue();
            // 路由key
            String routingKey = "info";
            // 绑定交换机和队列
            channel.queueBind(queueName,"mylog",routingKey);
            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));
                }
            });
        }
    }
}

      消费者2,绑定路由key为info和error

package com.lingaolu;

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

public class customer2 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 临时队列
            String queueName = channel.queueDeclare().getQueue();
            // 绑定交换机和队列
            channel.queueBind(queueName,"mylog","info");
            channel.queueBind(queueName,"mylog","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("消费者2=============="+new String(body));
                }
            });
        }
    }
}

      消费者3,绑定路由key为error

package com.lingaolu;

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

import java.io.IOException;

public class customer3 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 临时队列
            String queueName = channel.queueDeclare().getQueue();
            // 路由key
            String routingKey = "error";
            // 绑定交换机和队列
            channel.queueBind(queueName,"mylog",routingKey);
            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("消费者3=============="+new String(body));
                }
            });
        }
    }
}

      运行消费者1和消费者2和消费者3,接着运行生产者,当生产者的路由key为info时,只有绑定相同路由key的消费者1和消费者2接收到消息,当生产者的路由key为error时,只有绑定相同路由key的消费者2和消费者3接收到消息

4-5:Topics模型:动态路由模型,订阅模式Topics

      Topics类型的交换机ExchangeDirect相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topics类型交换机Exchange可以让队列在绑定RoutingKey的时候使用通配符!,这种模型RoutingKey一般都是由一个或多个单词组成,多个单词之间以“.”分割,例如:info.error.debug
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_MQ_38

通配符

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

      生产者,路由key为info.error.debug,交换机类型为topic

@Test
void sentMessage() throws IOException {
    Connection connection = RabbitMQUtils.getConnection();
    Channel channel = RabbitMQUtils.getChannel(connection);
    if(null != channel){
        String exchange = "myTopic";
        /**
         * 将通道声明指定为交换机
         * 参数1:交换机名称,不存在会自动创建
         * 参数2:交换机类型,topic:动态路由模式
         */
        channel.exchangeDeclare(exchange,BuiltinExchangeType.TOPIC);
        // 路由key
        String routingKey = "info.error.debug";
        // 向交换机发送消息
        channel.basicPublish(exchange,routingKey,null,("消息内容"+routingKey).getBytes());
    }
    RabbitMQUtils.closeChannelAndConnection(channel,connection);
}

      消费者1,路由key为info.#,交换机类型为topic

package com.lingaolu;

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

public class customer1 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 临时队列
            String queueName = channel.queueDeclare().getQueue();
            // 路由key
            String routingKey = "info.#";
            // 绑定交换机和队列
            channel.queueBind(queueName,"myTopic",routingKey);
            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));
                }
            });
        }
    }
}

      消费者2,路由key为*.error.*,交换机类型为topic

package com.lingaolu;

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

public class customer2 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 临时队列
            String queueName = channel.queueDeclare().getQueue();
            // 路由key
            String routingKey = "*.error.*";
            // 绑定交换机和队列
            channel.queueBind(queueName,"myTopic",routingKey);
            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));
                }
            });
        }
    }
}

      消费者3,路由key为info.*,交换机类型为topic

package com.lingaolu;

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

import java.io.IOException;

public class customer3 {
    public static void main(String[] args)  throws IOException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = RabbitMQUtils.getChannel(connection);
        if(null != channel){
            // 临时队列
            String queueName = channel.queueDeclare().getQueue();
            // 路由key
            String routingKey = "info.*";
            // 绑定交换机和队列
            channel.queueBind(queueName,"myTopic",routingKey);
            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("消费者3=============="+new String(body));
                }
            });
        }
    }
}

      运行消费者1和消费者2和消费者3,接着运行生产者,由*和#通配符表示的含义,我们可以知道消费者1和消费者2可以接收到 x消息,而消费者3接收不到消息。

5:springBoot整合Rabbitmq

      引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

      yml配置

spring:
  application:
    name: springboot-rabbitmq
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    virtual-host: /test
    username: test
    password: 123

      配置好了之后,会提供一个模板RabbitTemplate,下面我们就针对几种模式进行举例,我们使用一个bean类Student来传输数据

package com.lingaolu.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
    private long id;
    private String name;
}

      使用lombok所以引入依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

5-1:"Hello World!"模型:简单生产者-消费者

      生产者

@Autowired
RabbitTemplate rabbitTemplate;

@Test
void sentMessage(){
    Student student = new Student(1, "呵呵");
    rabbitTemplate.convertAndSend("hello", student);
}

      消费者,真正创建队列的是在消费者

package com.lingaolu.component;

import com.lingaolu.bean.Student;
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;

// 注解到IOC容器
@Component
// 队列监听,并且创建队列
@RabbitListener(queuesToDeclare = @Queue(value = "hello",durable = "true",autoDelete = "true"))
public class RabbitMQHello {

    // 处理器。接收队列里的消息
    @RabbitHandler
    public void aa(Student student){
        System.out.println("message="+student);
    }
}

      启动项目消费者就注入到IOC容器,创建队列,从队列那消息,此时如果指向生产者的代码,消费者会从队列中拿到消息。

5-2:Work queues模型:工作队列

      生产者,循环生产消息,使用控制层接口来模拟

package com.lingaolu.controller;

import com.lingaolu.bean.Student;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Test {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/test")
    public String sentMessage(){
        Student student = new Student(0, "呵呵");
        for (int i = 1; i <=10 ; i++) {
            student.setId(i);
            rabbitTemplate.convertAndSend("hello", student);
        }
        return "ok";
    }
}

平均消费模式

      2个消费者队列,轮训获取队列里的消息

package com.lingaolu.component;

import com.lingaolu.bean.Student;
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;

// 注解到IOC容器
@Component
public class RabbitMQHello {

    // 消费者1
    @RabbitListener(queuesToDeclare = @Queue(value = "hello",durable = "true",autoDelete = "true"))
    public void aa1(Student student){
        System.out.println("message1="+student);
    }

    // 消费者2
    @RabbitListener(queuesToDeclare = @Queue(value = "hello",durable = "true",autoDelete = "true"))
    public void aa2(Student student){
        System.out.println("message2="+student);
    }
}

      启动项目访问接口可看到2个消费者平均接收到队列里的消息
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_RabbitMQ_39

确认机制和能者多劳消费模式

      yml配置文件变为

spring:
  application:
    name: springboot-rabbitmq
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    virtual-host: /test
    username: test
    password: 123
    # 发送确认
    publisher-confirm-type: correlated
    # 发送回调
    publisher-returns: true
    # 消费手动确认
    listener:
      direct:
        acknowledge-mode: manual
      simple:
        acknowledge-mode: manual
        #并发消费者初始化值
        concurrency: 1
        #并发消费者的最大值
        max-concurrency: 10
        #每个消费者每次监听时可拉取处理的消息数量
        #在单个请求中处理的消息个数,他应该大于等于事务数量(unack的最大数量)
        prefetch: 1
        # 是否支持重试
        retry:
          enabled: true

      2个消费者队列,手动确认接收消息,消费者2加了睡眠时间,用来模拟消费消息慢

package com.lingaolu.component;

import com.lingaolu.bean.Student;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

// 注解到IOC容器
@Component
public class RabbitMQHello {

    // 消费者1
    @RabbitListener(queuesToDeclare = @Queue(value = "hello",durable = "true",autoDelete = "true"))
    public void aa1(Student student, Message message, Channel channel) throws IOException {
        System.out.println("message1="+student);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
            //消费者告诉队列信息消费失败
            /**
             * 拒绝确认消息:
             * channel.basicNack(long deliveryTag, boolean multiple, boolean requeue) ;
             * deliveryTag:该消息的index
             * multiple:是否批量true:将一次性拒绝所有小于deliveryTag的消息
             * requeue:被拒绝的是否重新入队列
             */
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

    // 消费者2
    @RabbitListener(queuesToDeclare = @Queue(value = "hello",durable = "true",autoDelete = "true"))
    public void aa2(Student student, Message message, Channel channel) throws InterruptedException, IOException {
        Thread.sleep(4000);
        System.out.println("message2="+student);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}

      启动项目访问接口可看到,由于消费者2睡眠了,所以大部分消息都让消费者1消费了
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot_40

5-3:Publish/Subscribe模型:发布订阅模式,广播模型

      生产者

package com.lingaolu.controller;

import com.lingaolu.bean.Student;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Test {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/test")
    public String sentMessage(){
        Student student = new Student(1, "呵呵");
        // 交换机为myExchange
        rabbitTemplate.convertAndSend("myExchange","", student);
        return "ok";
    }
}

      消费者

package com.lingaolu.component;

import com.lingaolu.bean.Student;
import com.rabbitmq.client.BuiltinExchangeType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

// 注解到IOC容器
@Component
public class RabbitMQHello {

    // 消费者1
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,// 创建临时队列
                    exchange = @Exchange(value = "myExchange",type = ExchangeTypes.FANOUT)// 绑定交换机
            )
    })
    public void aa1(Student student){
        BuiltinExchangeType.FANOUT.getType();
        System.out.println("message1="+student);
    }

    // 消费者2
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,// 创建临时队列
                    exchange = @Exchange(value = "myExchange",type = ExchangeTypes.FANOUT)
            )
    })
    public void aa2(Student student){
        System.out.println("message2="+student);
    }
}

      启动项目访问接口可看到2个消费者都能接收到队列里的消息
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot_41

5-4:Routing模型:路由模型,订阅模式Direct

      生产者,我把路由的key当成参数,这样方便测试路由

package com.lingaolu.controller;

import com.lingaolu.bean.Student;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Test {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/test")
    public String sentMessage(String routingKey){
        Student student = new Student(1, "呵呵");
        // 交换机为myExchange
        rabbitTemplate.convertAndSend("myLog",routingKey, student);
        return "ok";
    }
}

      消费者,2消费者绑定不同的路由

package com.lingaolu.component;

import com.lingaolu.bean.Student;
import com.rabbitmq.client.BuiltinExchangeType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

// 注解到IOC容器
@Component
public class RabbitMQHello {

    // 消费者1
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,// 创建临时队列
                    exchange = @Exchange(value = "myLog",type = ExchangeTypes.DIRECT),  // 绑定交换机
                    key={"info","debug"}    // 路由
            )
    })
    public void aa1(Student student){
        BuiltinExchangeType.FANOUT.getType();
        System.out.println("message1="+student);
    }

    // 消费者2
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,// 创建临时队列
                    exchange = @Exchange(value = "myLog",type = ExchangeTypes.DIRECT),
                    key={"info","error"}
            )
    })
    public void aa2(Student student){
        System.out.println("message2="+student);
    }
}

      启动项目访问接口,通过不同的传参进行路由设置,可见符合路由的消费者才能接收到消息

5-5:Topics模型:动态路由模型,订阅模式Topics

      生产者,路由key为info.error.debug,交换机类型为topic

package com.lingaolu.controller;

import com.lingaolu.bean.Student;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Test {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/test")
    public String sentMessage(){
        Student student = new Student(1, "呵呵");
        // 交换机为myExchange
        rabbitTemplate.convertAndSend("myTopic","info.error.debug", student);
        return "ok";
    }
}

      消费者,3个消费者的路由key分别为info.#.error.info.*

package com.lingaolu.component;

import com.lingaolu.bean.Student;
import com.rabbitmq.client.BuiltinExchangeType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

// 注解到IOC容器
@Component
public class RabbitMQHello {

    // 消费者1
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,// 创建临时队列
                    exchange = @Exchange(value = "myTopic",type = ExchangeTypes.TOPIC),  // 绑定交换机
                    key={"info.#"}    // 路由
            )
    })
    public void aa1(Student student){
        BuiltinExchangeType.FANOUT.getType();
        System.out.println("message1="+student);
    }

    // 消费者2
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,// 创建临时队列
                    exchange = @Exchange(value = "myTopic",type = ExchangeTypes.TOPIC),
                    key={"*.error.*"}
            )
    })
    public void aa2(Student student){
        System.out.println("message2="+student);
    }

    // 消费者3
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,// 创建临时队列
                    exchange = @Exchange(value = "myTopic",type = ExchangeTypes.TOPIC),
                    key={"info.*"}
            )
    })
    public void aa3(Student student){
        System.out.println("message3="+student);
    }
}

      启动项目访问接口,因为消费者3不符合路由额规则,所以只有消费者3没有收到消息
RabbitMQ,采用当前最新版RabbitMQ 3.8.12,Erlang 23.2_整合springboot_42