← All articles
Backend1 min read

Async Messaging with RabbitMQ and Spring

When you need routing, work queues, and acknowledgements more than a replayable log, RabbitMQ fits. Here's the Spring AMQP essentials.

S

Swapnika Voora

Author

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.

RabbitConfig.java
@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.

OrderPublisher.java
@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.

ShippingConsumer.java
@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.

#java#spring-boot#rabbitmq#messaging

More in Backend