在Fanout模式中,一条消息,会被所有的消费者都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。
在Direct模型下,消息的发送方在向Exchange发送消息时,需要指定消息的Routingkey,并且队列与交换机的绑定时也需要指定一个Routingkey。Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routingkey进行判断,只有队列的Routingkey与消息的Routingkey完全一致,队列才会接收到消息。
1.开发生产者
public class Provider {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMqUtil.getConnection();
Channel channel = connection.createChannel();
String exchange = "routingexchange";
//将通道声明指定交换机 参数1:指明交换机名称 参数2:交换机的类型 fanout广播类型
channel.exchangeDeclare(exchange,"direct");
//发送消息
String routingKey = "error";
channel.basicPublish(exchange,routingKey,null,("这是routingexchange发布的"+routingKey+"消息").getBytes());
//释放资源
RabbitMqUtil.closeConnectionAndChannel(channel,connection);
}
}
2.开发消费者(error)
public class Consumer1 {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMqUtil.getConnection();
//获取连接通道
Channel channel = connection.createChannel();
String exchange = "routingexchange";
//通道绑定交换机
channel.exchangeDeclare(exchange,"direct");
//临时队列
String queueName = channel.queueDeclare().getQueue();
//基于RoutingKey绑定交换机和队列
channel.queueBind(queueName,exchange,"error");
channel.basicConsume(queueName,true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("consumer1得到:"+new String(body));
}
});
//注意这里不能关闭通道和连接,因为要一直监听
}
}
3.开发消费者(Info、error、warning)
public class Consumer2 {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMqUtil.getConnection();
//获取连接通道
Channel channel = connection.createChannel();
String exchange = "routingexchange";
//通道绑定交换机
channel.exchangeDeclare(exchange,"direct");
//临时队列
String queueName = channel.queueDeclare().getQueue();
//基于RoutingKey绑定交换机和队列
channel.queueBind(queueName,exchange,"info");
channel.queueBind(queueName,exchange,"error");
channel.queueBind(queueName,exchange,"warning");
channel.basicConsume(queueName,true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("consumer2得到:"+new String(body));
}
});
//注意这里不能关闭通道和连接,因为要一直监听
}
}
4.结果分析
消费者1只能接收消息路由为error的消息,而消费者2可以接收消息路由为info、error、warning的消息。