Springboot整合

交换机间路由、绑定多个路由键,匿名队列等

2021-11-02  本文已影响0人  垃圾简书_吃枣药丸

# 演示目标:

target

实现的效果为: 消息只投递到e-pre交换机,e-pre交换机根据消息routingKey分别将消息路由到交换机e-a, e-be-ab,再由这三个交换机将消息路由到绑定的队列上。

# 代码实现

package com.futao.techsharingmq.basic.concept.simple.book;

import com.futao.techsharingmq.basic.concept.simple.MqChannelUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 将exchange与exchange绑定
 * 将exchange的消息路由到另外的exchange,再路由到queue
 *
 * @author futao@gmail.com
 * @date 2021/11/2
 */
public class Exchange2Exchange {
    public static void main(String[] args) throws IOException {
        // 获取channel
        Channel channel = MqChannelUtils.createChannel();

        //定义topic类型的交换机e-pre
        channel.exchangeDeclare("e-pre", BuiltinExchangeType.TOPIC);

        // 定义fanout类型的交换机e-a, e-b, e-ab
        channel.exchangeDeclare("e-a", BuiltinExchangeType.FANOUT);
        channel.exchangeDeclare("e-b", BuiltinExchangeType.FANOUT);
        channel.exchangeDeclare("e-ab", BuiltinExchangeType.FANOUT);

        // 将e-pre和三个交换机绑定,并且指定路由规格,注意这里使用的是#exchangeBind方法
        channel.exchangeBind("e-a", "e-pre", "r-a");
        channel.exchangeBind("e-b", "e-pre", "r-b");
        // 绑定多个路由键r-a,r-b
        channel.exchangeBind("e-ab", "e-pre", "r-a");
        channel.exchangeBind("e-ab", "e-pre", "r-b");

        // 定义匿名队列并获取生成的匿名队列名称
        String queue1 = channel.queueDeclare().getQueue();
        // 将匿名队列与三个交换机绑定
        channel.queueBind(queue1, "e-a", "");
        String queue2 = channel.queueDeclare().getQueue();
        channel.queueBind(queue2, "e-b", "");
        String q3 = channel.queueDeclare().getQueue();
        channel.queueBind(q3, "e-ab", "");

        // 发送100条消息
        for (int i = 0; i < 1000; i++) {
            // 生成路由键
            String rk = "r-b";
            if (i % 2 == 0) {
                rk = "r-a";
            }
            //将消息投递到e-pre交换机
            channel.basicPublish("e-pre", rk, new AMQP.BasicProperties(), "success".getBytes(StandardCharsets.UTF_8));
        }
    }
}

# 结果

queue
exchange
e-pre
e-ab
queue
上一篇下一篇

猜你喜欢

热点阅读