rabbitmq中confirm和return模式的使用

本文介绍了RabbitMQ的confirm和return两种模式。confirm模式下,消息到达交换机即触发回调,成功或失败都会通知。return模式则在消息未能成功投递到队列时触发回调,确保消息传递的可靠性。
  • 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 模式事务模式。如果你使用的是 confirm 模式,可以设置消息的确认超时时间,如果消息在超时时间内没有被确认,则可以进行重试。 具体来说,可以使用 `channel.confirm_select()` 方法开启 confirm 模式,并使用 `add_on_return_callback()` 方法为未确认的消息设置回调函数。在回调函数中,可以根据需要进行消息的重发或其他操作。 下面是一个简单的示例代码: ``` import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() # 开启 confirm 模式 channel.confirm_select() # 设置未确认消息的回调函数 def on_return(channel, method, properties, body): print("Message returned: %s" % body) # 进行重试或其他操作 channel.add_on_return_callback(on_return) # 发送消息 channel.basic_publish(exchange='', routing_key='test', body='Hello, world!', mandatory=True) # 等待消息确认 if not channel.wait_for_confirmation(): # 消息未被确认,进行重试或其他操作 pass connection.close() ``` 在上面的代码中,我们使用 `mandatory=True` 将消息标记为必须路由到队列中,如果无法路由则会返回给生产者。如果消息被返回,则会触发回调函数 `on_return()` 进行处理。在 `wait_for_confirmation()` 方法中等待消息的确认,如果在超时时间内消息未被确认,则会返回 False,此时可以进行重试或其他操作
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值