In our code we have attached RabbitTemplate.ReturnCallback() to get notification of not routed messages from consumer and it is working fine for the fixed queue.
But in case of synchronous publish by using rabbitTemplate.sendAndReceive, after receiving message when consumer tries to send response through dynamic queue , ReturnCallback is called always.
Is it the expected behavior? Do we have any way to handle not routed message for dynamic queue.
Below are the beans created in my project , here we have attached one consumer to the queue "test", which receive the published "Message" from queue "test" then put a response to "reply-to" queue.
@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" );
}
};
}
Rest end point to publish message synchronously to queue "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();
}