I have a very basic Spring Boot
application that is publishing two messages to RabbitMQ
using headers
exchange. Both the exchange
and queue
is getting created but the message is not reaching to the queue. I do not see any exception either.
I googled around but could not find any examples related to this.
BasicApplication.java
@SpringBootApplication
public class BasicApplication {
public static final String QUEUE_NAME = "helloworld.header.red.q";
public static final String EXCHANGE_NAME = "helloworld.header.x";
//here the message ==> xchange ==> queue1, queue2
@Bean
public List<Object> headerBindings() {
Queue headerRedQueue = new Queue(QUEUE_NAME, false);
HeadersExchange headersExchange = new HeadersExchange(EXCHANGE_NAME);
return Arrays.asList(headerRedQueue, headersExchange,
bind(headerRedQueue).to(headersExchange).where("color").matches("red"));
}
public static void main(String[] args) {
SpringApplication.run(BasicApplication.class, args).close();
}
}
Producer.java
@Component
public class Producer implements CommandLineRunner {
@Autowired
private RabbitTemplate rabbitTemplate;
@Override
public void run(String... args) throws Exception {
MessageProperties messageProperties = new MessageProperties();
//send a message with "color: red" header in the queue, this will show up in the queue
messageProperties.setHeader("color", "red");
//MOST LIKELY THE PROBLEM IS HERE
//BELOW MESSAGE IS NOT LINKED TO ABOVE messageProperties OBJECT
this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, "", "Hello World !");
//send another message with "color: gold" header in the queue, this will NOT show up in the queue
messageProperties.setHeader("color", "gold");
this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, "", "Hello World !");
}
}
You're correct in that the MessageProperties
you're creating aren't being used.
Trying building a Message
that leverages MessageProperties
with the help of a MessageConverter
.
Example:
MessageProperties messageProperties = new MessageProperties();
messageProperties.setHeader("color", "red");
MessageConverter messageConverter = new SimpleMessageConverter();
Message message = messageConverter.toMessage("Hello World !", messageProperties);
rabbitTemplate.send("helloworld.header.x", "", message);