Rabbitmq消息队列:Topic话题模式简单应用

一、生产者

  声明topic话题模式的交换机,分别发送几条消息到不同的路由key

package test.topic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import utils.RabbitmqConUtil;

public class Give {

    //定义交换机
    private final static String EXCHANGE = "test-topic";

    public static void main(String[] args) throws Exception {
        //创建连接和通道
        Connection connection = RabbitmqConUtil.getConnection();
        Channel channel = connection.createChannel();
        //声明交换机(类型topic->话题模式)
        channel.exchangeDeclare(EXCHANGE,"topic");
        //发送消息到交换机(交换机无法持久化,如果消息没有及时接收,重启后容易丢失数据)
        channel.basicPublish(EXCHANGE,"GetOne.oneMessage",null,"这是发送给GetOne.oneMessage的消息".getBytes());
        channel.basicPublish(EXCHANGE,"GetThree.oneMessage.value",null,"这是发送给GetThree.oneMessage.value的消息".getBytes());
    }

}

  这几个消息的路由key嵌套了好几层,方便对于消息进行话题的分类整合。

二、消费者

  topic模式的重点在于:

  针对于上面生产者消息发送的路由key,可以通过" * "和" # "等通配符来进行模糊匹配。

  " * "代表匹配一层,即直接匹配,比如a.*可以匹配到a.b,但是无法匹配到a.b.c。

  " # "代表多层匹配,比如a.#可以匹配到a.b,a.c.a.d,也可以匹配到a.b.c.d.e,一直向后扩展

  创建消费者GetOne:

package test.topic;

import com.rabbitmq.client.*;
import utils.RabbitmqConUtil;

import java.io.IOException;

public class GetOne {

    private final static String EXCHANGE = "test-topic";
    //定义本消费者需要用到的队列
    private final static String QUEUE = "test-topic-one";

    public static void main(String[] args) throws Exception{
        Connection connection = RabbitmqConUtil.getConnection();
        final Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(QUEUE,false,false,false,null);
        //将队列绑定到交换机(第二个参数是路由的key,需要多个的话就绑多个)
        channel.queueBind(QUEUE,EXCHANGE,"GetOne.*");
        channel.queueBind(QUEUE,EXCHANGE,"GetThree.#");
        channel.basicQos(1);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String str = new String(body);
                System.out.println("GetOne接收:" + str);
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(QUEUE,false,defaultConsumer);

    }
}

三、运行结果

  先运行生产者对交换机test-topic进行初始化。

  

  然后运行消费者GetOneGetOne.*GetThree.#两个通配规则的路由key绑定到交换机上。

  

  再次运行生产者发送消息,结果如下:

  

  两个消息都成功被GetOne接收。

  

posted @ 2023-11-03 17:05  我命倾尘  阅读(74)  评论(0编辑  收藏  举报