【RabbitMQ Learning Journey】Topics主题模式(通配符)

(内容来源于蚂蚁课堂)

topic模式实在路由key模式的基础上,使用了通配符来管理消费者接收消息。生产者P发送消息到交换机X,type=topic,交换机根据绑定队列的routing key的值进行通配符匹配

符号#:匹配一个或者多个词lazy.# 可以匹配lazy.irs或者lazy.irs.cor

符号*:只能匹配一个词lazy.* 可以匹配lazy.irs或者lazy.cor


Topic生产者:

package com.google.util.topic;

import com.google.util.MQConnectionUtils;
import com.google.util.config.Config;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

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

/**
 * @author wk
 * @Description:RabbitMQ 通配符模式(主题)
 * @date 2019/12/10 11:45
 **/
public class TopicProducer {

    //交换机名称
    private static String EXCHANGE_NAME = Config.TOPIC_EXCHANGE;

    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        Connection connection = MQConnectionUtils.newConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //生产者绑定交换机 (交换机名称,交换机类型)
        channel.exchangeDeclare(EXCHANGE_NAME, Config.exchangeType.topic);

        String routingKey = "msg.info";
        //String routingKey = "msg.info.email";
        System.out.println("通配符模式-生产者启动!");
        String msg = "[" + routingKey + "]RabbitMQ通配符模式的消息❤";
        System.out.println(msg);
        //发送消息
        channel.basicPublish(EXCHANGE_NAME, routingKey, null, msg.getBytes());
        //关闭通道和连接
        channel.close();
        connection.close();
    }
}

Topic消费者:

package com.google.util.topic;

import com.google.util.config.Config;
import com.google.util.MQConnectionUtils;
import com.rabbitmq.client.*;

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

/**
 * @author wk
 * @Description:通配符模式 邮件消费者
 * @date 2019/12/10 14:21
 **/
public class ConsumerEmailTopic {

    public static final String EMAIL_QUEUE = "EMAIL_TOPIC_QUEUE";
    private static String EXCHANGE_NAME = Config.TOPIC_EXCHANGE;

    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println("通配符模式-邮件消费者启动!");
        //建立连接
        Connection connection = MQConnectionUtils.newConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(EMAIL_QUEUE, false, false, false, null);
        //消费者绑定交换机 (队列名称,交换机名称,routing)
        channel.queueBind(EMAIL_QUEUE, EXCHANGE_NAME, "msg.#");
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("通配符模式-邮件消费者获取生产者的消息:" + new String(body, "UTF-8"));
            }
        };
        //自动应答
        channel.basicConsume(EMAIL_QUEUE, true, consumer);
    }
}
package com.google.util.topic;

import com.google.util.config.Config;
import com.google.util.MQConnectionUtils;
import com.rabbitmq.client.*;

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

/**
 * @author wk
 * @Description: 消费者
 * @date 2019/12/10 14:11
 **/
public class ConsumerSmsTopic {

    public static final String SMS_QUEUE = "SMS_TOPIC_QUEUE";
    private static String EXCHANGE_NAME = Config.TOPIC_EXCHANGE;

    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println("通配符模式-短信消费者启动!");
        //建立连接
        Connection connection = MQConnectionUtils.newConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //声明队列 (参数2 durable持久的)
        channel.queueDeclare(SMS_QUEUE, false, false, false, null);
        //消费者队列绑定交换机
        channel.queueBind(SMS_QUEUE, EXCHANGE_NAME, "msg.*");
        //消费监听消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("通配符模式-短信消费者获取生产者消息:" + msg);
            }
        };
        //自动应答
        channel.basicConsume(SMS_QUEUE, true, consumer);
    }
}

启动生产者,消费者,可以看到短信邮件消费者都收到了信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Key Features, Learn to administer, configure, and manage RabbitMQ instancesDiscover ways to secure and troubleshoot RabbitMQ instancesThis book is fully up-to-date with all the latest changes to version 3.5, Book Description, RabbitMQ is Open Source Message Queuing software based on the Advanced Message Queue Protocol Standard written in the Erlang Language. RabbitMQ is an ideal candidate for large-scale projects ranging from e-commerce and finance to Big Data and social networking because of its ease of use and high performance. Managing RabbitMQ in such a dynamic environment can be a challenging task that requires a good understanding not only of how to work properly with the message broker but also of its best practices and pitfalls., Learning RabbitMQ starts with a concise description of messaging solutions and patterns, then moves on to concrete practical scenarios for publishing and subscribing to the broker along with basic administration. This knowledge is further expanded by exploring how to establish clustering and high availability at the level of the message broker and how to integrate RabbitMQ with a number of technologies such as Spring, and enterprise service bus solutions such as MuleESB and WSO2. We will look at advanced topics such as performance tuning, secure messaging, and the internals of RabbitMQ. Finally we will work through case-studies so that we can see RabbitMQ in action and, if something goes wrong, we'll learn to resolve it in the Troubleshooting section., What you will learn, Apply messaging patterns using the message brokerAdminister RabbitMQ using the command line, management Web console, or management REST servicesCreate a cluster of scalable, and highly-available, RabbitMQ instancesUse RabbitMQ with the Spring Framework, MuleESB, WSO2, and Oracle databasesDeploy RabbitMQ using Puppet, Vagrant, or DockerFine-tune the performance of RabbitMQMonitor RabbitMQ using Nagios, Munin, or MonitSecure, troubleshoot, and extend RabbitMQ, About the Author, Martin Toshev is a software developer and Java enthusiast with more than eight years of experience and vast expertise originating from projects in areas such as enterprise Java, social networking, source code analysis, Internet of Things, and investment banking in companies such as Cisco and Deutsche Telekom. He is a graduate of computer science from the University of Sofia. He is also a certified Java professional (SCJP6) and a certified IBM cloud computing solution advisor. His areas of interest include a wide range of Java-related technologies (Servlets, JSP, JAXB, JAXP, JMS, JMX, JAX-RS, JAX-WS, Hibernate, Spring Framework, Liferay Portal, and Eclipse RCP), cloud computing technologies, cloud-based software architectures, enterprise application integration, and relational and NoSQL databases. Martin is one of the leaders of the Bulgarian Java Users group (BGJUG), a regular speaker at Java conferences, and one of the organizers behind the jPrime conference in Bulgaria (http://jprime.io/)., Table of Contents, Introducing RabbitMQDesign Patterns with RabbitMQAdministration, Confi guration, and ManagementClusteringHigh AvailabilityIntegrationsPerformance Tuning and MonitoringTroubleshootingSecurityInternalsContributing to RabbitMQ
RabbitMQ通配符工作模式是指使用Topic Exchange来实现路由选择的一种模式。在这种模式下,队列可以绑定到一个模式上,使用符号"#"匹配一个或多个词,而符号"*"匹配不多不少一个词。例如,"audit.#"能够匹配到"audit.irs.corporate",但是"audit."只会匹配到"audit.irs"。这种模式可以实现更灵活的消息路由,可以根据消息的一部分内容进行匹配,并将消息发送到符合条件的队列。详情可以参考RabbitMQ官方文档的教程。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [rabbitmq-通配符模式](https://blog.csdn.net/PacosonSWJTU/article/details/114504011)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [RabbitMq](https://download.csdn.net/download/weixin_38590567/14885852)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [05_RabbitMQ通配符匹配模式】](https://blog.csdn.net/qq_45037155/article/details/125743485)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值