前言
先上图回顾RabbitMQ的几种模型
Routing 之订阅模型-Direct(直连)
在Fanout模式中,一条消息,会被所有订阅的队列都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。
在Direct模型下:
- 队列与交换机的绑定,不能是任意绑定了,而是要指定一个
RoutingKey
(路由key) - 消息的发送方在 向 Exchange发送消息时,也必须指定消息的
RoutingKey
。 - Exchange不再把消息交给每一个绑定的队列,而是根据消息的
Routing Key
进行判断,只有队列的Routingkey
与消息的Routing key
完全一致,才会接收到消息 - P:生产者,向Exchange发送消息,发送消息时,会指定一个routing key。
- X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与routing key完全匹配的队列
- C1:消费者,其所在队列指定了需要routing key 为 error 的消息
- C2:消费者,其所在队列指定了需要routing key 为 info、error、warning 的消息
- 生产者
public class Provider {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMQUtils.getConnection();
//通道对象
Channel channel = connection.createChannel();
//通过通道去声明交换机 参数1:交换机名称 参数2:路由模式
channel.exchangeDeclare("logs_direct","direct");
//发送消息
//路由Key
String routerKey = "error";
channel.basicPublish("logs_direct",routerKey,null,("这是direct模型发布的基于 route key :["+routerKey+"]发送的消息").getBytes());
//释放资源
RabbitMQUtils.closeConnectionAndChanel(channel,connection);
}
}
消费者
public class Customser1 {
public static void main(String[] args) throws IOException {
//获取连接
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//通道声明交换机以及交换类型
channel.exchangeDeclare("logs_direct","direct");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//基于route key绑定队列和交换机
channel.queueBind(queue,"logs_direct","error");
//获取消费消息
channel.basicConsume(queue,true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1======"+new String(body));
}
});
}
}
** 消费者2**
public class Customer2 {
public static void main(String[] args) throws IOException {
//获取连接拿到通道
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机,以及交换机类型direct
channel.exchangeDeclare("logs_direct","direct");
//创建一个临时队列
String queue = channel.queueDeclare().getQueue();
//临时队列和交换机的绑定
channel.queueBind(queue,"logs_direct","info");
channel.queueBind(queue,"logs_direct","error");
channel.queueBind(queue,"logs_direct","warning");
//消费对象
channel.basicConsume(queue,true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者2======"+new String(body));
}
});
}
}
提示
结合代码和注释学习