简介
本节主要演示使用直连接类型,将同一个键绑定到多个队列上(多重绑定multiple bindings),此时满足键的队列都能收到消息,不满足的直接被丢弃。
生产者
@Test
public void produce() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(AMQP.PROTOCOL.PORT);
factory.setUsername("guest");
factory.setPassword("guest");
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
// 声明一个交换机,使用直连类型
String EXCHANGE_NAME = "exchange.direct.oneRoutingKey";
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
// 路由键名
String routingKey = "log";
// 队列数组名
String[] queues = {"queue1", "queue2"};
// 循环声明2个队列,并和同一个交换机、路由键绑定
for (int i = 0; i < queues.length; i++) {
channel.queueDeclare(queues[i], false, false, false, null);
channel.queueBind(queues[i], EXCHANGE_NAME, routingKey);
}
// 发布消息
String message = "Hello RabbitMQ--" + routingKey;
channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
channel.close();
conn.close();
}
消费者1
@Test
public void consume1() throws IOException, TimeoutException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(AMQP.PROTOCOL.PORT);
factory.setUsername("guest");
factory.setPassword("guest");
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
// 声明一个队列
String QUEUE_NAME = "queue1";
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("Consumer1 Wating Receive Message");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println("[C] received " + message + ",处理业务中...");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
Thread.sleep(1000000);
}
消费者2
@Test
public void consume2() throws IOException, TimeoutException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(AMQP.PROTOCOL.PORT);
factory.setUsername("guest");
factory.setPassword("guest");
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
// 声明一个队列
String QUEUE_NAME = "queue2";
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("Consumer2 Wating Receive Message");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println("[C] received " + message + ",处理业务中...");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
Thread.sleep(1000000);
}