官方文档
https://www.rabbitmq.com/getstarted.html
路由模式模型
生产者代码
public class Send {
private static final String EXCHANGE_NAME = "routing";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
// 声明exchange
channel.exchangeDeclare(EXCHANGE_NAME, "direct");
String errMsg = "error";
String successMsg = "success";
// 推送消息到交换机时携带key
String errorKey = "error";
channel.basicPublish(EXCHANGE_NAME, errorKey, null, errMsg.getBytes());
String successKey = "success";
channel.basicPublish(EXCHANGE_NAME, successKey, null, successMsg.getBytes());
channel.close();
connection.close();
}
}
消费者代码
public class Rec1 {
private static final String EXCHANGE_NAME = "routing";
private static final String QUEUE_NAME = "routing_queue";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
// 队列声明
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 交换机绑定,绑定交换机时携带key
String errorKey = "error";
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, errorKey);
// 接收到消息后的回调函数
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(LocalDateTime.now().toString() + " [x] Received '" + message + "'");
};
// 监听队列,每当队列中接收到新消息后会触发回调函数
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
public class Rec2 {
private static final String EXCHANGE_NAME = "routing";
private static final String QUEUE_NAME = "routing_queue";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
// 队列声明
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 交换机绑定,绑定交换机时携带key
String successKey = "success";
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, successKey);
// 接收到消息后的回调函数
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(LocalDateTime.now().toString() + " [x] Received '" + message + "'");
};
// 监听队列,每当队列中接收到新消息后会触发回调函数
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
结果
总结
如果需要开启路由模式,生产者需要做两件事
1.首先开启交换机的direct模式
channel.exchangeDeclare(EXCHANGE_NAME, "direct");
2.然后在发送消息时,携带上key
channel.basicPublish(EXCHANGE_NAME, KEY, null, errMsg.getBytes());
而消费者只需要做
绑定队列时携带上key
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, errorKey);