Day95.RabbitMQ:消息中间件: 安装配置、消息队列、三种订阅模式、Spring整合

目录

一、消息队列 MQ

二、RabbitMQ

1、安装 RabbitMQ

2、测试与配置

三、RabbitMQ入门

1. 生产者模块 rabbitme-producer 

2. 消费者模块 rabbitme-consumer

3, AMQP

四、Work queues 工作队列模式

五、订阅模式类型

1、Publish/Subscribe发布与订阅模式

2、Routing: 路由模式

3、Topics: 通配符模式

4. 总结 ★

六、Spring 整合RabbitMQ

1、生产者模块 producer

2、消费者模块 consumer

七、路由、通配符订阅模式整合 (topic交换机 fount交换机) 

1. 生产者 Producer:

2. 消费者Consumer : 


一、消息队列 MQ

MQ全称为Message Queue 消息队列(MQ) 是一种应用程序对应用程序的通信方法。

队列的主要作用是消除高并发访问高峰,加快网站的响应速度异步、解耦、削峰。

介绍:消息队列就是基础数据结构中的“先进先出”的一种数据机构。想一下,生活中买东西,需要排队,先排的人先买消费,就是典型的“先进先出”。可以起到缓冲的作用

 在项目中,可将一些无需即时返回且耗时的操作提取出来,进行异步处理,而这种异步处理的方式大大的节省了服务器的请求响应时间,从而提高了系统的吞吐量。

 场景说明:用户注册后,需要发注册邮件和注册短信

串行方式:

 并行方式: 

 消息队列:

QPS,PV,UV , PR

QPS即每秒查询率,是对一个特定的查询服务器在规定时间内所处理流量多少的衡量标准。

计算关系:

QPS = 并发量 / 平均响应时间

并发量 = QPS * 平均响应时间

原理:每天80%的访问集中在20%的时间里,这20%时间叫做峰值时间

公式:( 总PV数 * 80% ) / ( 每天秒数 * 20% ) = 峰值时间每秒请求数(QPS) 。

机器:峰值时间每秒QPS / 单台机器的QPS = 需要的机器 。

 什么是pv

PV(page view),即页面浏览量,或点击量;通常是衡量一个网络新闻频道或网站甚至一条网络新闻的主要指标。

 什么是uv
uv(unique visitor),指访问某个站点或点击某条新闻的不同IP地址的人数

 什么是PR值
PR值,即PageRank,网页的级别技术,用来标识网页的等级/重要性。级别从1到10级,10级为满分。PR值越高说明该网页越受欢迎(越重要)。

AMQP 和 JMS

AMQP是一种高级消息队列协议Advanced Message Queuing Protocol,更准确的说是一种binary wire-level protocol(链接协议)。这是其和JMS的本质差别,AMQP不从API层进行限定,而是直接定义网络交换的数据格式

JMS即Java消息服务(JavaMessage Service)应用程序接口,是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送消息,进行异步通信。

消息队列产品 

二、RabbitMQ

消息队列,它是一种应用程序之间的通信方法,消息队列在分布式系统开发中应用非常广泛。

RabbitMQ官方地址:Messaging that just works — RabbitMQ 

RabbitMQ提供了6种模式:简单模式,work模式 Publish/Subscribe发布与订阅模式Routing路由模式Topics主题模式,RPC远程调用模式(远程调用,不太算MQ;暂不作介绍);

 RabbitMQ 基础架构如下图:

Virtual Host 对交换机、队列进行创建与管理,类似于Mysql中的数据库

Exchange交换机只负责转发消息,无法存储,所以必须要与Queue进行绑定。 

相关概念:

Broker:接收和分发消息的应用,RabbitMQ Server就是 Message Broker

Virtual host:出于多租户和安全因素设计的,把 AMQP 的基本组件划分到一个虚拟的分组中,类似于网络中的 namespace 概念。当多个不同的用户使用同一个 RabbitMQ server 提供的服务时,可以划分出多个vhost,每个用户在自己的 vhost 创建 exchange/queue 等

Connection:publisher/consumer 和 broker 之间的 TCP 连接

Channel:如果每一次访问 RabbitMQ 都建立一个 Connection,在消息量大的时候建立 TCP Connection的开销将是巨大的,效率也较低。Channel 是在 connection 内部建立的逻辑连接,如果应用程序支持多线程,通常每个thread创建单独的 channel 进行通讯,AMQP method 包含了channel id 帮助客户端和message broker 识别 channel,所以 channel 之间是完全隔离的。Channel 作为轻量级的 Connection 极大减少了操作系统建立 TCP connection 的开销

Exchange:message 到达 broker 的第一站,根据分发规则,匹配查询表中的 routing key,分发消息到queue 中去。常用的类型有:direct (point-to-point)topic (publish-subscribe) and fanout (multicast)

Queue存储消息的容器,消息最终被送到这里等待 consumer 取走

Binding:exchange 和 queue 之间的虚拟连接,binding 中可以包含 routing key。Binding 信息被保存到 exchange 中的查询表中,用于 message 的分发依据

1、安装 RabbitMQ

安装前,先检查主机名,如果主机名太长服务器可能启动失败

查看主机名:hostname

修改主机名:vim /etc/hostname

添加主机名映射: vim /etc/hosts 

1.安装ErlangSocatRabbitMQ

①rpm -ivh erlang-21.3.8.9-1.el7.x86_64.rpm 

②rpm -ivh socat-1.7.3.2-1.el6.lux.x86_64.rpm

在安装rabbitmq之前需要先安装socat,否则,报错。

可以采用yum安装方式:yum install socat,我们这里采用rpm安装方式

③rpm -ivh rabbitmq-server-3.8.1-1.el7.noarch.rpm 

/usr/lib/rabbitmq/bin/ 

2.启用管理插件

rabbitmq-plugins enable rabbitmq_management

3.启动RabbitMQ

systemctl start rabbitmq-server.service

systemctl status rabbitmq-server.service

systemctl restart rabbitmq-server.service

systemctl stop rabbitmq-server.service 

4.查看进程

ps -ef | grep rabbitmq

2、测试与配置

  • 关闭防火墙:systemctl stop firewalld.service
  • 在web浏览器中输入地址:http://虚拟机ip:15672/  (需要开放15672、25672、5672端口)
  • 输入默认账号密码: guest : guest,guest用户默认不允许远程连接。

 

增加自定义账号

  1. 添加管理员账号密码:rabbitmqctl add_user admin admin
  2. 分配账号角色:rabbitmqctl set_user_tags admin administrator
  3. 修改密码:rabbitmqctl change_password admin 123456
  4. 查看用户列表:rabbitmqctl list_users

使用新账号登录,成功界面

管理界面标签页介绍

  1. overview:概览
  2. connections:无论生产者还是消费者,都需要与RabbitMQ建立连接后才可以完成消息的生产和消费,在这里可以查看连接情况
  3. channels:通道,建立连接后,会形成通道,消息的投递获取依赖通道。
  4. Exchanges:交换机,用来实现消息的路由
  5. Queues:队列,即消息队列,消息存放在队列中,等待消费,消费后被移除队列。

端口:

  1. 5672:rabbitMq的编程语言客户端连接端口
  2. 15672:rabbitMq管理界面端口
  3. 25672:rabbitMq集群的端口

卸载:

  1. rpm -qa | grep rabbitmq
  2. rpm -e rabbitmq-server

三、RabbitMQ入门

父工程rabbitmq引入依赖

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

1. 生产者模块 rabbitme-producer 

package com.atguigu.rabbitmq.simple;

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

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

/**
 * @Date 2022/7/2 10:28
 * @Author by:Plisetsky
 */
//生产者:往消息列队中发送消息
public class Producer {

    //声明队列名称
    //快捷键psfs
    public static final String QUEUE_NAME = "simple_queue";

    public static void main(String[] args) throws Exception {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.86.86"); //设置ip
        connectionFactory.setPort(5672); //设置端口
        connectionFactory.setVirtualHost("/"); //设置虚拟主机(默认名称/),注意用户需要虚拟机权限
        connectionFactory.setUsername("admin"); //设置用户名
        connectionFactory.setPassword("123456"); //设置密码
        //2.创建链接
        Connection connection = connectionFactory.newConnection();

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

        //4.声明队列
        /*
         * @param queue 队列名称
         * @param durable true 表示声明一个持久化队列 (持久化队列重启后依然存在)。建议true
         * @param exclusive true 声明一个排他队列 (只限于当前连接使用),建议false
         * @param autoDelete true 声明一个自动删除的队列 (长时间不使用服务器会删除这个队列),建议false
         * @param arguments other 队列的一些其他参数(属性值)
         */
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);

        //5.发送消息
        /*
         * @param exchange 指定交换机,往交换机上发送消息,简单消息模式无交换机,只需要设置空串即可
         * @param routingKey 队列与交换机绑定的名称,简单消息模式需要使用队列的名称作为绑定名称,这个名称称为routingKey(路由key)
         * @param props 消息属性设置,以及路由头信息
         * @param body 请求体:传递的数据

         */
        String msg = "hello,rabbit!";
        channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());


        //6.关闭链接 先关信道再关链接
        channel.close();
        connection.close();
    }
}

2. 消费者模块 rabbitme-consumer

package com.atguigu.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.io.PrintStream;

/**
 * @Date 2022/7/2 10:29
 * @Author by:Plisetsky
 */
//消费者:从消息队列中获取消息,处理消息的一端
public class MyConsumer {

    //声明队列名称
    public static final String QUEUE_NAME = "simple_queue";

    public static void main(String[] args) throws Exception {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.86.86"); //设置ip
        connectionFactory.setPort(5672); //设置端口
        connectionFactory.setVirtualHost("/"); //设置虚拟主机(默认名称/),注意用户需要虚拟机权限
        connectionFactory.setUsername("admin"); //设置用户名
        connectionFactory.setPassword("123456"); //设置密码
        //2.创建链接
        Connection connection = connectionFactory.newConnection();

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

        //4.声明队列 (防止消费者先启动生产者未启动,不存在创建一个新的,存在直接使用。参数需要与已创建的一致)
        /*
         * @param queue 队列名称
         * @param durable true 表示声明一个持久化队列 (持久化队列重启后依然存在)。建议true
         * @param exclusive true 声明一个排他队列 (只限于当前连接使用),建议false
         * @param autoDelete true 声明一个自动删除的队列 (长时间不使用服务器会删除这个队列),建议false
         * @param arguments other 队列的一些其他参数(属性值)
         */
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);

        //5.获取消息,处理消息
        Consumer consumer = new DefaultConsumer(channel){
            //匿名内部类,重写方法处理消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag : " + consumerTag);//消费者唯一标识
                System.out.println("Exchange : " + envelope.getExchange());//交换机名字
                System.out.println("RoutingKey : " + envelope.getRoutingKey());//路由key(路径,从哪到哪(队列名?))
                System.out.println("DeliveryTag : " + envelope.getDeliveryTag());//消息唯一标识(类似表数据主键)
                System.out.println("properties : " + properties);//消息属性或头信息
                System.out.println("body : " + new String(body,"UTF-8"));//消息本身内容
            }
        };
        /*
         * @param queue 队列名称
         * @param autoAck true 一次性确认多个消息,false需要手动确认 (acknowledged的缩写)
         * @param callback 消费者对象,Consumer接口类型
         */
        channel.basicConsume(QUEUE_NAME,true,consumer);

        //6.关闭链接 不管一直处理
        //channel.close();
        //connection.createChannel();
    }

}

3, AMQP

AMQP 一个提供统一消息服务的应用层标准高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计。

RabbitMQ是AMQP协议的Erlang的实现。

概念

说明

连接Connection

一个网络连接,比如TCP/IP套接字连接。

信道Channel

多路复用连接中的一条独立的双向数据流通道。为会话提供物理传输介质。一个连接可以创建多个信道

客户端Client

AMQP连接或者会话的发起者。AMQP是非对称的,客户端生产和消费消息,服务器存储和路由这些消息。

服务节点Broker

消息中间件的服务节点;一般情况下可以将一个RabbitMQ Broker看作一台RabbitMQ 服务器。

端点

AMQP对话的任意一方。一个AMQP连接包括两个端点(一个是客户端,一个是服务器)。

消费者Consumer

一个从消息队列里请求消息的客户端程序。

生产者Producer

一个向交换机发布消息的客户端应用程序。

在入门案例中:

  • 生产者发送消息
  1. 生产者创建连接(Connection),开启一个信道(Channel),连接到RabbitMQ Broker;
  2. 声明队列并设置属性;如是否排它,是否持久化,是否自动删除;
  3. 将路由键(空字符串)与队列绑定起来;
  4. 发送消息至RabbitMQ Broker;
  5. 关闭信道;
  6. 关闭连接;
  • 消费者接收消息
  1. 消费者创建连接(Connection),开启一个信道(Channel),连接到RabbitMQ Broker
  2. 向Broker 请求消费相应队列中的消息,设置相应的回调函数;
  3. 等待Broker投递响应队列中的消息,消费者接收消息;
  4. 确认(ack,自动确认)接收到的消息;
  5. RabbitMQ从队列中删除相应已经被确认的消息;
  6. 关闭信道;
  7. 关闭连接;

四、Work queues 工作队列模式

Work Queues与入门程序的简单模式相比,多了一个或一些消费端,多个消费端共同消费同一个队列中的消息。

  1. 在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是竞争的关系。
  2. Work Queues 对于任务过重或任务较多情况使用工作队列可以提高任务处理的速度。

应用场景:对于 任务过重或任务较多情况使用工作队列可以提高任务处理的速度,避免消息积压

1. 抽取工具类

package com.atguigu.rabbitmq.util;

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

public class ConnectionUtil {
    public static Connection getConnection() throws Exception {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost("192.168.86.86");
        //端口
        factory.setPort(5672);
        //设置账号信息,用户名、密码、vhost
        factory.setVirtualHost("/");
        factory.setUsername("admin");
        factory.setPassword("123456");
        // 通过工程获取连接
        Connection connection = factory.newConnection();
        return connection;
    }

    public static void main(String[] args) throws Exception {
        Connection con = ConnectionUtil.getConnection();
        System.out.println(con);
        //         amqp://admin@192.168.137.118:5672/
        con.close();
    }
}

2. 生产者

package com.atguigu.rabbitmq.work;

import com.atguigu.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

public class Producer {
    static final String QUEUE_NAME = "work_queue";
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();

        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME,true,false,false,null);

        for (int i = 1; i <= 10; i++) {
            String body = i+"hello rabbitmq~";
            channel.basicPublish("",QUEUE_NAME,null,body.getBytes());
        }

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

3. 消费者1

package com.atguigu.rabbitmq.work;

import com.atguigu.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;

//工作队列消息模式:好处,多个消费者消费同一个队列,可以实现快速消费,避免消息积压
//多个消费者消费对立消息时,是互斥的,同一个消息只能被一个消费者消费,不能被多个消费者消费
public class Consumer1 {
    static final String QUEUE_NAME = "work_queue";
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("body1:"+new String(body));
            }
        };
        channel.basicConsume(QUEUE_NAME,true,consumer);
    }
}

4. 消费者2 代码相同
  

五、订阅模式类型

前面2个案例中,只有3个角色:

  • P:生产者,也就是要发送消息的程序
  • C:消费者:消息的接受者,会一直等待消息到来。
  • queue:消息队列,图中红色部分

而在订阅模型中,多了一个exchange角色,而且过程略有变化:

  • P:生产者,也就是要发送消息的程序,但是不再发送到队列中,而是发给X(交换机)
  • C:消费者,消息的接受者,会一直等待消息到来。
  • Queue:消息队列,接收消息、缓存消息。
  • Exchange:交换机,图中的X。一方面,接收生产者发送的消息。另一方面,知道如何处理消息,例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作,取决于Exchange的类型。Exchange有常见以下3种类型
    • Fanout:广播,将消息交给所有绑定到交换机的队列
    • Direct:定向,把消息交给符合指定routing key 的队列
    • Topic:通配符,把消息交给符合routing pattern(路由模式) 的队列

1、Publish/Subscribe发布与订阅模式

 发布订阅模式:
1、每个消费者监听自己的队列。
2、生产者将消息发给broker,由交换机将消息转发到绑定此交换机的每个队列,每个绑定交换机的队列都可以接收到消息。

1. 生产者

package com.atguigu.rabbitmq.fanout;

import com.atguigu.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Producer {
    public static void main(String[] args) throws Exception {

        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        /*
       exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)
       参数:
        1. exchange:交换机名称
        2. type:交换机类型
            DIRECT("direct"),:定向
            FANOUT("fanout"),:扇形(广播),发送消息到每一个与之绑定队列。
            TOPIC("topic"),通配符的方式
            HEADERS("headers");参数匹配
        3. durable:是否持久化
        4. autoDelete:自动删除
        5. internal:内部使用。 一般false
        6. arguments:参数
        */
        String exchangeName = "test_fanout";
        //5. 创建交换机
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT,true,false,false,null);
        //6. 创建队列
        String queue1Name = "test_fanout_queue1";
        String queue2Name = "test_fanout_queue2";
        channel.queueDeclare(queue1Name,true,false,false,null);
        channel.queueDeclare(queue2Name,true,false,false,null);
        //7. 绑定队列和交换机
        /*
        queueBind(String queue, String exchange, String routingKey)
        参数:
            1. queue:队列名称
            2. exchange:交换机名称
            3. routingKey:路由键,绑定规则
                如果交换机的类型为fanout ,routingKey设置为""
         */
        channel.queueBind(queue1Name,exchangeName,"");
        channel.queueBind(queue2Name,exchangeName,"");

        String body = "日志信息:张三调用了findAll方法...日志级别:info...";
        //8. 发送消息
        channel.basicPublish(exchangeName,"",null,body.getBytes());

        //9. 释放资源
        channel.close();
        connection.close();
    }
}

2. 消费者1

package com.atguigu.rabbitmq.fanout;

import com.atguigu.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;

public class Consumer1 {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        String queue1Name = "test_fanout_queue1";
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("body1:"+new String(body));
                System.out.println("将日志信息打印到控制台.....");
            }
        };
        channel.basicConsume(queue1Name,true,consumer);
    }
}

3. 消费者2 相同

2、Routing: 路由模式

路由模式特点:

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


图解:

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

 1. 生产者

public class Producer {
    public static void main(String[] args) throws Exception {
       Connection connection = ConnectionUtil.getConnection();
       Channel channel = connection.createChannel();
       String exchangeName = "test_direct";
       // 创建交换机
       channel.exchangeDeclare(exchangeName,BuiltinExchangeType.DIRECT,true,false,false,null);
       // 创建队列
       String queue1Name = "test_direct_queue1";
       String queue2Name = "test_direct_queue2";
        // 声明(创建)队列
       channel.queueDeclare(queue1Name,true,false,false,null);
       channel.queueDeclare(queue2Name,true,false,false,null);
       // 队列绑定交换机
        // 队列1绑定error
        channel.queueBind(queue1Name,exchangeName,"error");
        // 队列2绑定info error warning
        channel.queueBind(queue2Name,exchangeName,"info");
        channel.queueBind(queue2Name,exchangeName,"error");
        channel.queueBind(queue2Name,exchangeName,"warning");

        String message = "日志信息:张三调用了delete方法.错误了,日志级别warning";
        // 发送消息
        channel.basicPublish(exchangeName,"error",null,message.getBytes());
        System.out.println(message);

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

2. 消费者1

package com.atguigu.rabbitmq.routing;

import com.atguigu.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;

public class Consumer1 {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        String queue1Name = "test_direct_queue1";
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("body1:"+new String(body));
                System.out.println("将日志信息打印到控制台.....");
            }
        };
        channel.basicConsume(queue1Name,true,consumer);
    }
}

3、Topics: 通配符模式

Topic类型与Direct相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符

Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert

通配符规则:

#:匹配零个或多个词

*:匹配不多不少恰好1个词

1. 生产者

public class Producer {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        String exchangeName = "test_topic";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC,true,false,false,null);

        String queue1Name = "test_topic_queue1";
        String queue2Name = "test_topic_queue2";
        channel.queueDeclare(queue1Name,true,false,false,null);
        channel.queueDeclare(queue2Name,true,false,false,null);
        // 绑定队列和交换机
        /**
         *  参数:
             1. queue:队列名称
             2. exchange:交换机名称
             3. routingKey:路由键,绑定规则
                 如果交换机的类型为fanout ,routingKey设置为""
         */
        // routing key  系统的名称.日志的级别。
        //需求: 所有error级别的日志存入数据库,所有order系统的日志存入数据库
        channel.queueBind(queue1Name,exchangeName,"#.error");
        channel.queueBind(queue1Name,exchangeName,"order.*");
        channel.queueBind(queue2Name,exchangeName,"*.*");
        String body = "日志信息:张三调用了findAll方法...日志级别:info...";
        //发送消息goods.info,goods.error
        channel.basicPublish(exchangeName,"order.info.error",null,body.getBytes());
        channel.close();
        connection.close();
    }
}

2. 消费者

package com.atguigu.rabbitmq.topic;

import com.atguigu.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;

public class Consumer1 {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        String queue1Name = "test_topic_queue1";
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("body1:"+new String(body));
            }
        };
        channel.basicConsume(queue1Name,true,consumer);
    }
}

4. 总结 ★

1、简单模式 HelloWorld
一个生产者、一个消费者,不需要设置交换机(使用默认的交换机)

其实是有一个隐藏的交换机,路由key与队列名称保持一致

2、工作队列模式 Work Queue
一个生产者、多个消费者(竞争关系),不需要设置交换机(使用默认的交换机)

3、发布订阅模式(广播) Publish/subscribe
需要设置类型为fanout的交换机,并且交换机和队列进行绑定,当发送消息到交换机后,交换机会将消息发送到绑定的队列

4、路由模式(定向模式) Routing
需要设置类型为direct的交换机,交换机和队列进行绑定,并且指定routing key,当发送消息到交换机后,交换机会根据routing key将消息发送到对应的队列

5、通配符模式(主题类型交换机) Topic
需要设置类型为topic的交换机,交换机和队列进行绑定,并且指定通配符方式的routing key,当发送消息到交换机后,交换机会根据routing key将消息发送到对应的队列

六、Spring 整合RabbitMQ

1、生产者模块 producer

1.添加依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
    </dependencies>
    <!--编译插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

2.配置整合

rabbitmq.properties 配置链接参数

rabbitmq.host=192.168.86.86
rabbitmq.port=5672
rabbitmq.username=admin
rabbitmq.password=123456
rabbitmq.virtual-host=/

spring-rabbitmq.xml 整合配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <!--加载属性配置文件-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!--创建 connectionFactory 对象-->
    <rabbit:connection-factory id="connectionFactory"
                               host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"></rabbit:connection-factory>

    <!--创建RabbitAdmin对象,用于管理交换机队列 需引用connectionFactory-->
    <rabbit:admin connection-factory="connectionFactory"></rabbit:admin>

    <!--声明队列 (简单模型没有交换机)-->
    <rabbit:queue id="spring_queue" name="spring_queue" durable="true"
                                                        exclusive="false"
                                                        auto-delete="false"
                                                        auto-declare="true"></rabbit:queue>

    <!--创建RabbitTemplate对象,用于操作消息-->
    <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"></rabbit:template>

</beans>

3.Test测试 发送消息

@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath:/spring-rabbitmq.xml")
public class ProducerTest {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Test
    public void testSend(){
        rabbitTemplate.convertAndSend("spring_queue","spring rabbit");

    }
}

2、消费者模块 consumer

1. 添加依赖 (与生产者相同)

2. 配置整合

rabbitmq.properties 配置链接参数

rabbitmq.host=192.168.86.86
rabbitmq.port=5672
rabbitmq.username=admin
rabbitmq.password=123456
rabbitmq.virtual-host=/

spring-rabbitmq.xml 整合配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <!--加载属性配置文件-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!--创建 connectionFactory 对象-->
    <rabbit:connection-factory id="connectionFactory"
                               host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"></rabbit:connection-factory>

    <!--指定 创建监听器-->
    <bean id="springQueueListener" class="com.atguigu.rabbitmq.listener.SpringQueueListener"></bean>

    <!--监听器绑定队列-->
    <rabbit:listener-container connection-factory="connectionFactory">
        <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
    </rabbit:listener-container>

</beans>

3. 创建消息监听器

public class SpringQueueListener implements MessageListener {

    @Override
    public void onMessage(Message message) {
        try {
            //信息数据
            String msg = new String(message.getBody(),"UTF-8");
            System.out.println("msg : "+msg);
            
            //信息属性 (路由名称、路由键、队列名等..)
            MessageProperties messageProperties = message.getMessageProperties();
            System.out.println("messageProperties"+messageProperties);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

4. 测试

@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath:/spring-rabbitmq.xml")
public class ConsumerTest {

    @Test
    public void testRun() throws InterruptedException {
        while (true){ //使测试方法不退出,Ioc容器不退出,监听器一直监听队列

            Thread.sleep(1000);
        }
    }
}

七、路由、通配符订阅模式整合 (topic交换机 fount交换机) 

1. 生产者 Producer:

1. 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <!--加载属性配置文件-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!--创建 connectionFactory 对象-->
    <rabbit:connection-factory id="connectionFactory"
                               host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"></rabbit:connection-factory>

    <!--创建RabbitAdmin对象,用于管理交换机队列 需引用connectionFactory-->
    <rabbit:admin connection-factory="connectionFactory"></rabbit:admin>

    <!--声明队列 (简单模型没有交换机) auto-declare 不存在则自动创建-->
    <rabbit:queue id="spring_queue" name="spring_queue" durable="true"
                                                        exclusive="false"
                                                        auto-delete="false"
                                                        auto-declare="true"></rabbit:queue>

    <!--创建RabbitTemplate对象,用于操作消息-->
    <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"></rabbit:template>


    <!--实验2:用于演示fount交换机发送消息处理-->
    <!--延迟: fanout 广播类型交换机使用,不存在则自动创建-->
    <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"></rabbit:queue>
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>

    <!--交换机声明-->
    <rabbit:fanout-exchange name="spring_fanout_exchange" auto-declare="true">
        <!--将队列与交换机绑定-->
        <rabbit:bindings>
            <rabbit:binding queue="spring_fanout_queue_1"></rabbit:binding>
            <rabbit:binding queue="spring_fanout_queue_2"></rabbit:binding>
        </rabbit:bindings>
    </rabbit:fanout-exchange>

    <!--实验3:用于演示topic交换机发送消息处理-->
    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~实验三 通配符;*匹配一个单词,#匹配多个单词 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>

    <rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
        <rabbit:bindings>
            <rabbit:binding pattern="atguigu.*" queue="spring_topic_queue_star"/>
            <rabbit:binding pattern="atguigu.#" queue="spring_topic_queue_well"/>
            <rabbit:binding pattern="guigu.#" queue="spring_topic_queue_well2"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>
</beans>

2. 测试方法

    //测试fanout 交换机类型
    @Test
    public void testSend2(){
        rabbitTemplate.convertAndSend("spring_fanout_exchange","","fanout message");
    }

    /**
     * 通配符
     * 交换机类型为 topic
     * 匹配路由键的通配符,*表示一个单词,#表示多个单词
     * 绑定到该交换机的匹配队列能够收到对应消息
     */
    @Test
    public void topicTest(){
        /**
         * 参数1:交换机名称
         * 参数2:路由键名
         * 参数3:发送的消息内容
         */
        rabbitTemplate.convertAndSend("spring_topic_exchange", "atguigu.bj", "发送到spring_topic_exchange交换机atguigu.bj的消息");
        rabbitTemplate.convertAndSend("spring_topic_exchange", "atguigu.bj.1", "发送到spring_topic_exchange交换机atguigu.bj.1的消息");
        rabbitTemplate.convertAndSend("spring_topic_exchange", "atguigu.bj.2", "发送到spring_topic_exchange交换机atguigu.bj.2的消息");
        rabbitTemplate.convertAndSend("spring_topic_exchange", "guigu.cn", "发送到spring_topic_exchange交换机guigu.cn的消息");
    }

 通配符匹配测试:

2. 消费者Consumer : 

1. 配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <!--加载属性配置文件-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!--创建 connectionFactory 对象-->
    <rabbit:connection-factory id="connectionFactory"
                               host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"></rabbit:connection-factory>

    <!--实验1:简单消息模型 用于处理消息的消费者-->
    <bean id="springQueueListener" class="com.atguigu.rabbitmq.listener.SpringQueueListener"></bean>

    <!--实验2: 用于演示fount交换机发送消息处理-->
    <bean id="fanoutListener1" class="com.atguigu.rabbitmq.listener.FanoutListener1"></bean>
    <bean id="fanoutListener2" class="com.atguigu.rabbitmq.listener.FanoutListener2"></bean>

    <!--实验3: 用于演示topic交换机发送消息处理-->
    <bean id="topicListenerStar" class="com.atguigu.rabbitmq.listener.TopicListenerStar"/>
    <bean id="topicListenerWell" class="com.atguigu.rabbitmq.listener.TopicListenerWell"/>
    <bean id="topicListenerWell2" class="com.atguigu.rabbitmq.listener.TopicListenerWell2"/>

    <!--监听器绑定队列 这样列队中消息就被监听器处理到-->
    <rabbit:listener-container connection-factory="connectionFactory">
        <!--实验1:简单消息模型-->
        <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>

        <!--实验2:用于演示fount交换机发送消息处理-->
        <rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/>
        <rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>

        <!--实验3:用于演示topic交换机发送消息处理-->
        <rabbit:listener ref="topicListenerStar" queue-names="spring_topic_queue_star"/>
        <rabbit:listener ref="topicListenerWell" queue-names="spring_topic_queue_well"/>
        <rabbit:listener ref="topicListenerWell2" queue-names="spring_topic_queue_well2"/>
    </rabbit:listener-container>


</beans>

2. 消息监听器实现,略。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值