011 mandatory参数

一.概述

  在前面说明发送消息的basicPublish方法之中存在一个参数,那就是mandatory参数.

  本次,我们说明一下这个参数的作用.


二 . mandatory 参数

  我们可以这样理解这个参数,当我们发送一个消息的时候,如果交换机根本无法找到对应的消息队列的时候应该怎么办?

  [1]方式一 : 直接丢掉这个消息

  [2]方式二 : 把这个消息返回给生产者.

到底采用哪一个行为,取决为mandatory参数的设置.(是否完整性)

当mandatory设置为false,那么出现了无法找到队列的时候,直接就丢失消息了.

当mandatory设置为true的时候,生产者需要创建一个addReturnListener的方法添加一个监听器来收回到消息.


三 .代码的演示 

public class MandatoryTest {

    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtils.getConnection();

        Channel channel = connection.createChannel();

        // 声明一个交换机
        channel.exchangeDeclare("mandatory", "direct", false, false, false, null);

        channel.queueDeclare("queue", true, false, false, null);

        // 设置绑定
        channel.queueBind("queue", "mandatory", "abc");
        
        // 发送的消息根本没有队列
        channel.basicPublish("mandatory", "123", true, false, null, "trek".getBytes());

        // 设置一个监听器
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                    AMQP.BasicProperties properties, byte[] body) throws IOException{
                System.out.println("消息没有接受到===" + new String(body));
            }

        });

    }
}

我们创建了一个交换机,然后绑定了一个队列,但是我们设置的绑定键和路由键是不匹配的,因此会执行我们的addReturnListener方法.

 
原文地址:https://www.cnblogs.com/trekxu/p/9778563.html