channel.basicPublish("", "",true, null, message.getBytes(StandardCharsets.UTF_8));
当发布消息时,有一个mandatory参数,参见源方法:
void basicPublish(String exchange, String routingKey, boolean mandatory, BasicProperties props, byte[] body)
mandatory为true时,表示如果消息没有被正确路由,消息将退回消息的生产者,生产者需要添加监听器:
channel.addReturnListener((replyCode, replyText, exchange, routingKey, properties, body)
-> System.out.println(String.format("消息返回监听: %s", new String(body))));
我们知道在rabbitmq中,消息生产者其实并不关心消息队列,只需将消息发布至exchange,并指定routingKey路由队列,当routingKey配置不正确时,消息无法路由到指定队列时,生产者将会通过监听收到broker退回的消息。
public class Producer {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
String message = "Hello World!";
channel.basicPublish("", "",true, null, message.getBytes(StandardCharsets.UTF_8));
channel.addReturnListener((replyCode, replyText, exchange, routingKey, properties, body)
-> System.out.println(String.format("消息返回监听: %s", new String(body))));
System.out.println(" [x] Sent '" + message + "'");
}
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
System.out.println(scanner.next());
}
}
}
如上定义了队列hello,在消息发布时未指定routingKey,生产者将收到被退回的消息,当mandatory参数为false时,未被正确路由的消息将会直接被丢弃。