Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read headers in RabbitMQ in Java?

Tags:

java

rabbitmq

I have some properties that I would like to read from previously set message headers. I did this:

 Delivery delivery = consumer.nextDelivery();
 Map<String, Object> headers = delivery.getProperties().getHeaders();

Problem is, headers have weird types - like LongString for example. Is there any helper class that would allow me to easily convert headers to anything more useful?

like image 367
korda Avatar asked Nov 24 '15 14:11

korda


1 Answers

You must put Headers in your Message:

MessageProperties props = MessagePropertiesBuilder.newInstance().setContentType(MessageProperties.CONTENT_TYPE_JSON).build();
props.setHeader("headerKey1", "headerValue1");

Message msg = new Message("{'body':'value1','body2':value2}".getBytes(), props);        

rabbitTemplate.send("exchange.direct.one", new String(), msg);

For read the headers of Message inbound from Rabbit Queue:

import org.springframework.amqp.core.Message;
    import org.springframework.amqp.core.MessageListener;

    public class MessagesHandler implements MessageListener {

        public void onMessage(Message message) {
            Map<String, Object> headers = message.getMessageProperties().getHeaders();
            for (Map.Entry<String, Object> header : headers.entrySet())
            {
                System.out.println(header.getKey() + " : " + header.getValue());
            }
        }
    }
like image 123
dmotta Avatar answered Oct 12 '22 11:10

dmotta