在RabbitMQ中发布时给出不正确的(不存在的)队列名称

时间:2018-04-25 17:54:32

标签: java rabbitmq spring-amqp spring-rabbit spring-rabbitmq

我使用AyncRabbitTemplate发布消息。在发布时提供不正确的(不存在的)队列名称 - 它会以静默方式丢弃该消息。

我已尝试启用"确认"和"授权"在AyncRabbitTemplate上添加了所需的回调方法,如下所示:

@Bean
AsyncRabbitTemplate template() {
    RabbitTemplate rabbit = rabbitTemplate();
    rabbit.setChannelTransacted(true);         //to throw error when channel shuts down in case of incorrect exchange names

    AsyncRabbitTemplate asyncRabbitTemplate = new AsyncRabbitTemplate(rabbit, rpcReplyMessageListenerContainer(connectionFactory()));
    asyncRabbitTemplate.setEnableConfirms(true);
    asyncRabbitTemplate.setMandatory(true);         //if the message cannot be delivered to a queue an AmqpMessageReturnedException will be thrown
    return asyncRabbitTemplate;
}

@Bean
public SimpleMessageListenerContainer rpcReplyMessageListenerContainer(ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer(connectionFactory);
    simpleMessageListenerContainer.setQueueNames(Constants.REPLY_QUEUE);
    simpleMessageListenerContainer.setTaskExecutor(Executors.newCachedThreadPool());
    simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO);
    return simpleMessageListenerContainer;
}

@Bean
public RabbitTemplate rabbitTemplate() {
    return new RabbitTemplate(connectionFactory());
}

@Bean
public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
    return connectionFactory;
}

回调方法为:

RabbitConverterFuture<String> future = this.asyncRabbitTemplate.convertSendAndReceive("",Constants.SNS_QUEUE, "This is the request message ",new MessagePostProcessor() {

        @Override
        public Message postProcessMessage(Message message) {
            message.getMessageProperties().setTimestamp(new Date());
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
            return message;
        }
    });


    ListenableFuture<Boolean> future2 = future.getConfirm();
    future2.addCallback(new ListenableFutureCallback<Boolean>() {

        @Override
        public void onSuccess(Boolean result) {
            System.out.println("Publish Result " + result);

        }

        @Override
        public void onFailure(Throwable ex) {
            System.out.println("Publish Failed: " + ex);

        }
    });

1 个答案:

答案 0 :(得分:1)

the documentation中所述,您必须在连接工厂上启用返回的消息。

send不会抛出异常,但无法传递的消息将返回ReturnCallback(如果强制为真)。

确认不会发送无法投递的邮件。只有在经纪人遇到某种问题时才会收到否定确认;它们很少见。