1.模型图
实现过程:与发布订阅模式相比较,交换机不再将里面的消息发送给每一个它知道的队列,由于发布者再发布时多加了一个路由键,因此队列要能够接受消息必须改队列的路由键与发布时的一致才能接收到。
2.代码实现
生产者
public class Send {
public static void main(String[] args) throws IOException {
// 获取连接
Connection connection = MqUtil.getConnection();
// 创建通道
Channel channel = connection.createChannel();
// 声明交换机
/*
* 参数1:交换机名称
* 参数2:交换机类型,共四个direct,fanout,topic,headers,路由模式下是direct
* 参数3:是否持久化
* 参数4:是否自动删除
* 参数5:是否内置,true表示是内置的交换器, 客户端程序无法直接发送消息到这个交换器中, 只能通过交换器路由到交换器这个方式
* 参数6; 路由器其他 参数的设置,参考queueDeclare参数详解
* */
channel.exchangeDeclare("directTest", BuiltinExchangeType.DIRECT,true,false,false,null);
// 发布消息
String routingKey = "test2";
channel.basicPublish("directTest",routingKey,null,"direct test".getBytes());
// 关闭资源
MqUtil.close(channel,connection);
}
}
消费者1
public class Recv1 {
public static void main(String[] args) throws IOException {
Connection connection = MqUtil.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("directTest", BuiltinExchangeType.DIRECT,true,false,false,null);
// 获取一个临时队列:该队列特点:不持久化,排他,自动删除,也可以自己声明一个
String queueName = channel.queueDeclare().getQueue();
// 绑定队列: 只绑定routingkey为 test1
/*
* 参数1:队列名称
* 参数2:交换机名称
* 参数3:路由键
* 参数4:额外参数,参考queueDeclare参数详解
* */
channel.queueBind(queueName,"directTest","test1",null);
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(new String(body));
}
});
}
}
消费者2
public class Recv2 {
public static void main(String[] args) throws IOException {
Connection connection = MqUtil.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("directTest", BuiltinExchangeType.DIRECT,true,false,false,null);
// 获取一个临时队列:该队列特点:不持久化,排他,自动删除,也可以自己声明一个
String queueName = channel.queueDeclare().getQueue();
// 绑定队列:绑定routingkey为 test1和 test2
/*
* 参数1:队列名称
* 参数2:交换机名称
* 参数3:路由键
* 参数4:额外参数,参考queueDeclare参数详解
* */
channel.queueBind(queueName,"directTest","test1",null);
channel.queueBind(queueName,"directTest","test2",null);
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(new String(body));
}
});
}