target
e-pre
是类型为topic的交换机,与其绑定的有e-a
交换机,路由键为r-a
e-b
交换机,路由键为r-b
e-ab
交换机,路由键为r-a
和r-b
e-a
, e-b
, e-ab
交换机类型都为fanout,分别有q-a
,q-b
,q-ab
与其绑定。实现的效果为:消息只投递到
e-pre
交换机,e-pre
交换机根据消息routingKey
分别将消息路由到交换机e-a
,e-b
和e-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));
}
}
}
server-named
exclusive
, autodelete
, non-durable
queue。e-pre
交换机e-a
, e-b
和e-ad
交换机e-pre
和三个交换机绑定,并且指定路由规格,注意这里使用的是#exchangeBind
方法e-pre
交换机,其中500条的路由键为r-a
,另外500条的路由键为r-b
。queue
exchange
e-pre
e-ab
queue
消息被自动删除
队列被删除
绑定关系被删除