- confirm模式
开启confirm模式channel.confirmSelect();
这种模式,消息到达交换机时触发,若成功/失败到达交换机时,调用成功/失败回调函数。
import com.rabbitmq.client.*;
import java.io.IOException;
public class Sender {
public static void main(String[] args) {
ConnectionFactory factory = RabbitmqUtils.getConnectionFactory();
Connection connection;
Channel channel;
try {
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare("direct-queue", false, false, false, null);
channel.confirmSelect();
channel.addConfirmListener(new ConfirmListener() {
public void handleAck(long deliveryTag, boolean multiple) throws IOException {
System.out.println("ack:deliveryTag:" + deliveryTag + ",multiple:" + multiple);
}
public void handleNack(long deliveryTag, boolean multiple) throws IOException {
System.out.println("nack:deliveryTag:" + deliveryTag + ",multiple:" + multiple);
}
});
for (int i = 0; i < 100; i++) {
channel.basicPublish("", "direct-queue-1", null, "hello world".getBytes());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
只要到达了交换机(此处""是默认交换机),就会调用回调方法。
- return模式
只有成功到达了交换机且未到达队列才会触发回调函数。
basicPublish方法参数boolean mandatory默认是false,需要设置为true。
package fun.gosuncn.test1;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Sender {
public static void main(String[] args) {
ConnectionFactory factory = RabbitmqUtils.getConnectionFactory();
Connection connection;
Channel channel;
try {
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare("direct-queue", false, false, false, null);
channel.addReturnListener(new ReturnListener() {
@Override
public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.err.println("---------handle return----------");
System.err.println("replyCode: " + replyCode);
System.err.println("replyText: " + replyText);
System.err.println("exchange: " + exchange);
System.err.println("routingKey: " + routingKey);
System.err.println("properties: " + properties);
System.err.println("body: " + new String(body));
}
});
for (int i = 0; i < 100; i++) {
channel.basicPublish("", "direct-queue-1", true, null, "hello world".getBytes());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
channel.basicPublish("", “direct-queue-1”, true, null, “hello world”.getBytes());
第三个参数设置为true。

本文介绍了RabbitMQ的confirm和return两种模式。confirm模式下,消息到达交换机即触发回调,成功或失败都会通知。return模式则在消息未能成功投递到队列时触发回调,确保消息传递的可靠性。
1033

被折叠的 条评论
为什么被折叠?



