RabbitMQ is a traditional message broker built around exchanges, queues, and routing keys. Where Kafka shines at replayable event logs, RabbitMQ excels at work queues and flexible routing with per-message acknowledgement.
Declare the topology as beans
Spring AMQP can declare exchanges, queues, and bindings on startup. This keeps your messaging topology in code and version control.
@Configuration
public class RabbitConfig {
@Bean
public TopicExchange ordersExchange() {
return new TopicExchange("orders");
}
@Bean
public Queue shippingQueue() {
return QueueBuilder.durable("shipping").build();
}
@Bean
public Binding binding(Queue shippingQueue, TopicExchange ordersExchange) {
return BindingBuilder.bind(shippingQueue)
.to(ordersExchange).with("order.placed");
}
}Publish with a routing key
RabbitTemplate sends to an exchange with a routing key; the broker decides
which queues receive it.
@Service
public class OrderPublisher {
public void publish(OrderEvent event) {
template.convertAndSend("orders", "order.placed", event);
}
}Consume with acknowledgement
@RabbitListener binds a method to a queue. With manual acks, a message is only
removed once you confirm success.
@RabbitListener(queues = "shipping")
public void onOrder(OrderEvent event) {
shipping.schedule(event.orderId());
}Takeaways
- Model exchanges, queues, and bindings as beans for reproducible topology.
- Routing keys let one publish fan out to many queues.
- Durable queues plus acknowledgements prevent message loss on crashes.
Configure a dead-letter exchange so messages that repeatedly fail get parked for inspection instead of looping forever.