RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)

时间:2022-06-29 01:14:33



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

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


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

通配符规则:

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

举例:

item.#:能够匹配item.insert.abc 或者 item.insertitem.*:只能匹配item.insert

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)

图注:

  • 红色Queue:绑定的是usa.# ,因此凡是以 usa.开头的routing key 都会被匹配到
  • 黄色Queue:绑定的是#.news ,因此凡是以 .news结尾的 routing key 都会被匹配

一、生产者Module

(1)pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>rabbitmq-demo</artifactId>
        <groupId>net.xiaof</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>rabbitmq-producer</artifactId>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--rabbitmq java 客户端-->
        <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>

</project>

(2)生产者类

package net.xiaof.producer;

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

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

/**
 * @author zhangxh
 * @Description: 生产者(通配符/主题模式)
 * @date 2020-12-16
 */
public class Producer_Topics {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂,设置相关连接参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.116.161");
        factory.setPort(5672);
        factory.setVirtualHost("/myhost");
        factory.setUsername("xiao");
        factory.setPassword("xiao");

        //2. 创建连接Connection
        Connection connection = factory.newConnection();

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

        //4. 声明交换机exchange
        /**
         * 【API说明】:
         * exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)
         * 参数:
         * (1)String exchange:交换机名称
         * (2)BuiltinExchangeType type:交换机类型
         *      DIRECT("direct"):定向
         *      FANOUT("fanout"):扇形(广播),发送消息到每一个与之绑定队列。
         *      TOPIC("topic"):通配符的方式
         *      HEADERS("headers"):参数匹配
         * (3)boolean durable:是否持久化
         * (4)boolean autoDelete:是否自动删除
         * (5)boolean internal:内部使用,一般用false
         * (6)Map<String, Object> arguments:参数
         */
        String exchangeName = "topics_exchange";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC, true, false, false, null);

        //5. 声明队列Queue
        /**
         * 【API说明】:
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
         * 参数:
         * (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
         * (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
         * (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
         * (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
         * (5)Map<String, Object> arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
         */
        String queueName1 = "topics_queue1";
        String queueName2 = "topics_queue2";
        channel.queueDeclare(queueName1, true, false, false, null);
        channel.queueDeclare(queueName2, true, false, false, null);

        //6. 绑定队列和交换机
        /**
         * 【API说明】:
         * queueBind(String queue, String exchange, String routingKey)
         * 参数:
         * (1)String queue:队列名称。
         * (2)String exchange:交换机名称
         * (3)String routingKey:路由键,绑定规则(使用了routingKey时,发布消息方法basicPublish(...)也需要指定相关routingKey)
         *      如果交换机的类型为fanout ,routingKey设置为""
         *      如果交换机的类型为direct ,需要设置routingKey
         */
        //需求: 所有error级别的日志存入数据库,所有order系统的日志存入数据库
        channel.queueBind(queueName1, exchangeName, "#.error");
        channel.queueBind(queueName1, exchangeName, "order.*");
        channel.queueBind(queueName2, exchangeName, "*.*");

        //7. 发布消息
        /**
         * 【API说明】:
         * basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
         * 参数:
         * (1)String exchange:交换机名称。简单模式下交换机会使用默认的 ""
         * (2)String routingKey:路由key
         * (3)BasicProperties props:配置信息
         * (4)byte[] body:发送消息数据
         */
        String bodyMsg = "日志信息:马云调用了add方法";
        channel.basicPublish(exchangeName, "os.sys", null, bodyMsg.getBytes());

        //8. 关闭资源
        channel.close();
        connection.close();

    }

}

二、消费者Module

(1)pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>rabbitmq-demo</artifactId>
        <groupId>net.xiaof</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>rabbitmq-consumer</artifactId>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--rabbitmq java客户端-->
        <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>

</project>

(2)消费者类1

package net.xiaof.consumer;

import com.rabbitmq.client.*;

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

/**
 * @author zhangxh
 * @Description: 消费者1
 * @date 2020-12-16
 */
public class Consumer_Topic1 {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂,设置相关连接参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.116.161");
        factory.setPort(5672);
        factory.setVirtualHost("/myhost");
        factory.setUsername("xiao");
        factory.setPassword("xiao");

        //2. 创建连接Connection
        Connection connection = factory.newConnection();

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

        //4. 接收消息
        Consumer consumer = new DefaultConsumer(channel) {
            /**
             * 回调方法,当收到消息后,会自动执行该方法
             * void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
             * 参数:
             * (1)String consumerTag:标识
             * (2)Envelope envelope:获取一些信息,交换机,路由key...
             * (3)AMQP.BasicProperties properties:配置信息
             * (4)byte[] body:数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
//                System.out.println("consumerTag:" + consumerTag);
//                System.out.println("Exchange:" + envelope.getExchange());
//                System.out.println("RoutingKey:" + envelope.getRoutingKey());
//                System.out.println("properties:" + properties);
                System.out.println("body:" + new String(body));
                System.out.println("Consumer_Topic1.class:将日志信息存入数据库");

            }
        };
        /**
         * 【API说明】:
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数:
         * (1)String queue:队列名称
         * (2)boolean autoAck:是否自动确认
         * (3)Consumer callback:回调对象
         */
        String queueName1 = "topics_queue1";
        String queueName2 = "topics_queue2";
        channel.basicConsume(queueName1, true, consumer);//这里消费队列“pubsub_queue1”的消息

        //5.关闭资源(消费者需要监听生产者消息,这里不关闭)

    }

}

(3)消费者类2

package net.xiaof.consumer;

import com.rabbitmq.client.*;

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

/**
 * @author zhangxh
 * @Description: 消费者2
 * @date 2020-12-16
 */
public class Consumer_Topic2 {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂,设置相关连接参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.116.161");
        factory.setPort(5672);
        factory.setVirtualHost("/myhost");
        factory.setUsername("xiao");
        factory.setPassword("xiao");

        //2. 创建连接Connection
        Connection connection = factory.newConnection();

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

        //4. 接收消息
        Consumer consumer = new DefaultConsumer(channel) {
            /**
             * 回调方法,当收到消息后,会自动执行该方法
             * void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
             * 参数:
             * (1)String consumerTag:标识
             * (2)Envelope envelope:获取一些信息,交换机,路由key...
             * (3)AMQP.BasicProperties properties:配置信息
             * (4)byte[] body:数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
//                System.out.println("consumerTag:" + consumerTag);
//                System.out.println("Exchange:" + envelope.getExchange());
//                System.out.println("RoutingKey:" + envelope.getRoutingKey());
//                System.out.println("properties:" + properties);
                System.out.println("body:" + new String(body));
                System.out.println("Consumer_Topic2.class:将日志信息打印到控制台");

            }
        };
        /**
         * 【API说明】:
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数:
         * (1)String queue:队列名称
         * (2)boolean autoAck:是否自动确认
         * (3)Consumer callback:回调对象
         */
        String queueName1 = "topics_queue1";
        String queueName2 = "topics_queue2";
        channel.basicConsume(queueName2, true, consumer);//这里消费队列“pubsub_queue1”的消息

        //5.关闭资源(消费者需要监听生产者消息,这里不关闭)

    }

}

三、测试

注意: 这里第一次需要先启动生产者类,队列的声明(创建),已经交给生产者,启动后,所声明队列会注册在RabbitMq的虚拟主机中,消费者只需要从指定的队列中消费消息即可。

如果第一次先启动消费者,会报异常:找不到要消费的队列。

(1)先启动生产者类,生产者声明(创建)队列

在RabbitMQ的web管理端,查看队列情况:

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


(2)再分别启动 “消费者1 ” 和 “消费者2 ” 进行消费消息

启动所有消费者,然后使用生产者发送消息;在消费者对应的控制台可以查看到生产者发送对应routing key对应队列的消息;到达按照需要接收的效果;并且这些routing key可以使用通配符。

关键代码:

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


运行结果:

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


(3)修改“生产者 ”代码如下

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


运行结果:

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


按照规则,只有队列2中有消息,且能被消费:

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


(4)在RabbitMQ的web管理端,查看路由绑定情况:

RabbitMQ消息中间件(六):工作模式之主题(通配符)模式(Topic)


三、小结

Topic主题模式可以实现 Publish/Subscribe发布与订阅模式 Routing路由模式 的功能;只是Topic在配置routing key 的时候可以使用通配符,显得更加灵活。