I'm trying to create a RabbitMQ configuration class using Spring Framework. The documentation does not say anything on how to setup multiple topics in a TopicExchange. How do I do that? So far, I have this Java code but I'm not clear on how to setup multiple topics in the binding method below since it only returns one binding. Would I not need multiple bindings if I need multiple topics?
@Configuration
@EnableRabbit
public class MessageReceiverConfiguration {
final static String queueName = "identity";
final static String topic1 = "NewUserSignedUp";
final static String topic2 = "AccountCreated";
@Autowired
RabbitTemplate rabbitTemplate;
@Bean
Queue queue() {
return new Queue(queueName, false);
}
@Bean
TopicExchange exchange() {
return new TopicExchange("DomainEvents");
}
@Bean
Binding binding(Queue queue, TopicExchange exchange) {
// How to setup multiple topics?
return BindingBuilder.bind(queue).to(exchange).with(topic1);
}
@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(queueName);
container.setMessageListener(listenerAdapter);
container.setAcknowledgeMode(AcknowledgeMode.AUTO);
return container;
}
@Bean
MessageReceiver receiver() {
return new MessageReceiver();
}
@Bean
MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
}
You can define multiple binding by changing Binding
function to return a list instead of a single Binding
object.
@Bean
List<Binding> bindings() {
return Arrays.AsList(BindingBuilder.bind(queue()).to(exchange()).with(topic1),
BindingBuilder.bind(queue()).to(exchange()).with(topic2));
}
Tip: You do not need to pass queue and exchange as method params. You can directly refer the bean methods to pass the information of exchange and queue.
Refer documentation for more details.
List<Binding> bindings()
not supported by spring boot 2.+ versions.
This one works;
@Bean
public Declarables bindings() {
return new Declarables(
BindingBuilder
.bind(bookingAddQueue())
.to(bookingExchange())
.with("add")
.noargs(),
BindingBuilder
.bind(bookingEditQueue())
.to(bookingExchange())
.with("edit")
.noargs());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With