Search code examples
javaxmlspringrabbitmqamqp

How to get MessageProperties with Spring RabbitMQ MessageListener


I'm creating a Spring MessageListenerAdapter that is listening to a Queue for XML messages.

This is my amqp configuration:

    @Bean()
    SimpleMessageListenerContainer simpleMessageListenerContainer(ConnectionFactory connectionFactory,
                                                                  MessageListenerAdapter messageListener) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames("queueA", "queueB");
        container.setMessageListener(messageListener);
        container.setChannelTransacted(true);
        return container;
    }

    @Bean
    MessageListenerAdapter messageListener(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

Currently the receiving of messages works, but only if the returning type of my listener is String.

With following Listener I receive my XML messages, so that's fine. But I'm not able to get the messageProperties of the original message:

@Component
public class Receiver {

    public void receiveMessage(String message) {
        try {
            if (message.isEmpty()) {
                log.info("---> Received message is empty!");
            } else {
                log.info("---> Received message: <{}>", message);
            }
        } catch (Exception e) {
            log.error("---> Exception in processing receiv                                              
                   ed message!", e);
        }
    }                                                                                                                            
}                                 

If I change the return type of receiveMessage() to bytes[] or Message, I get the following error message:

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Failed to invoke target method 'receiveMessage' with argument type = [class java.lang.String], value = [{myXmlMessage}]

I've already tried MessageConverters, but I'm a newbie with RabbitMQ. Thanks for any help!


Solution

  • I found the solution by myself: By default a MessageConverter is used for the MessageListenerAdapter. To prevent this, the MessageConverter must be set to null. Now it works and I receive the plain message with all messageProperties!

    @Bean
    MessageListenerAdapter messageListener(Receiver receiver) {
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(receiver, "receiveMessage");
        messageListenerAdapter.setMessageConverter(null);
        return messageListenerAdapter;
    }