Set message header in rabbitmq while sending

Rajat Goyal picture Rajat Goyal · Oct 4, 2016 · Viewed 10.9k times · Source

I want to set message header while sending a message to rabbit. I am using below code, but confused how to set message header in it.

public static <T> void sendMessage(String routingKey,final Object message,Class<T> type){
    DefaultClassMapper typeMapper = new DefaultClassMapper();
    typeMapper.setDefaultType(type);

    Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
    converter.setClassMapper(typeMapper);

    RabbitTemplate template = new RabbitTemplate(getConnectionFactory));
    template.setMessageConverter(converter);

    template.convertAndSend(routingKey, message);
}

In above method i am simply arguementing java POJO object and its type to send. I want to know where should i set message header here.

How to listen the message properties at listener end?

Answer

Gary Russell picture Gary Russell · Oct 4, 2016

Java 8:

template.convertAndSend(routingKey, message, m -> {
    m.getMessageProperties().getHeaders().put("foo", "bar");
    m.getMessageProperties().setPriority(priority);        
    return m;
});

Java 6,7:

template.convertAndSend(routingKey, message, new MessagePostProcessor() {

    @Override
    public Message postProcessMessage(Message m) throws AmqpException {
        m.getMessageProperties().getHeaders().put("foo", "bar");
        m.getMessageProperties().setPriority(priority);        
        return m;
    }

});