始终在动态队列发布中调用RabbitTemplate.ReturnCallback()

时间:2016-06-10 13:24:27

标签: spring rabbitmq spring-amqp spring-rabbitmq

在我们的代码中,我们附加了RabbitTemplate.ReturnCallback()以获取来自使用者的未路由消息的通知,并且它对于固定队列工作正常。

但是在使用rabbitTemplate.sendAndReceive进行同步发布的情况下,当使用者尝试通过动态队列发送响应时收到消息后,始终会调用ReturnCallback

这是预期的行为吗? 我们是否有办法处理动态队列的未路由消息。

下面是我项目中创建的bean,这里我们将一个使用者连接到队列“test”,它从队列“test”接收已发布的“Message”,然后对“reply-to”进行响应队列中。

@Bean
SimpleMessageListenerContainer container( ConnectionFactory connectionFactory ) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory( connectionFactory );
    container.setQueueNames( "test" );
    container.setMessageListener( exampleListener() );
    return container;
}

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

@Bean
public RabbitTemplate rabbitTemplate( ConnectionFactory connectionFactory ) {
    RabbitTemplate rabbitTemplate = new RabbitTemplate( connectionFactory );
    rabbitTemplate.setMandatory( true );
    ((CachingConnectionFactory)rabbitTemplate.getConnectionFactory()).setPublisherReturns( true );
    rabbitTemplate.setReturnCallback( new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage( Message arg0, int arg1, String arg2, String arg3, String arg4 ) {
            System.out.println( "Returned message  " + arg0 );
            System.out.println( "Returned replyText  " + arg2 );
           }
    } );
    return rabbitTemplate;
}
@Bean
public RabbitAdmin rabbitAdmin( ConnectionFactory connectionFactory ){
    return  new RabbitAdmin( connectionFactory );
}


@Bean
public MessageListener exampleListener() {
    return new MessageListener() {
        public void onMessage( Message message ) {
            System.out.println( "received: " + message );
            RabbitTemplate rabbitTemplate = rabbitTemplate( rabbitConnectionFactory() );

            // sending message to reply-to queue( dynamic queue in case of synchronous publish)
            // even though the queue exist and messaage successfully published  , RabbitTemplate.ReturnCallback() is called 
            rabbitTemplate.convertAndSend( message.getMessageProperties().getReplyTo(), "response from consumer" );

        }
    };
}

休息结束点同步发布消息到队列“test”

/**

 * publish  Message to Queue.
 *
 * @return response 

 */
@RequestMapping ( value = "/publish", method = RequestMethod.POST )
public String sendMsgToQueue( ) {
    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setCorrelationId("101".getBytes());
    rabbitTemplate.setReplyTimeout( 30000 ); // timeout
    return rabbitTemplate.sendAndReceive( "test", new SimpleMessageConverter().toMessage( "message to test", messageProperties ) ).toString();

}

0 个答案:

没有答案