Coding a Consumer

Learn how to write a RabbitMQ consumer.

Writing a RabbitMQ consumer

With the producer nicely defined in a WebFlux controller, it’s time to switch gears and focus on writing a RabbitMQ consumer. Spring AMQP actually has multiple options. The absolute simplest approach available is to use AmqpTemplate.receive(queueName). It’s probably not the best solution, though, especially for high-volume environments.

@Service //1
public class SpringAmqpItemService {
private static final Logger log =
LoggerFactory.getLogger(SpringAmqpItemService.class);
private final ItemRepository repository; //2
public SpringAmqpItemService(ItemRepository repository) {
this.repository = repository;
}
}
Consuming AMQP messages reactively

Here’s a breakdown of the code above:

  1. In line 1, @Service ensures that an instance of this class is created when launched.

  2. In line 7, the ItemRepository is injected through constructor injection.

There’s also a Logger, which we’ll soon put to good use. But first, it’s time to configure what’s probably the most convenient way to listen for RabbitMQ messages using Spring AMQP:

@RabbitListener( //1
ackMode = "MANUAL",
bindings = @QueueBinding( //2
value = @Queue, //3
exchange = @Exchange("hacking-spring-boot"), //4
key = "new-items-spring-amqp")) //5
public Mono<Void> processNewItemsViaSpringAmqp(Item item) { //6
log.debug("Consuming => " + item);
return this.repository.save(item).then(); //7
}
Registering a RabbitMQ message listener

Here’s a breakdown of the code above:

  1. In line 1, @RabbitListener informs Spring AMQP to configure a message listener, ready to consume messages.
  2. In line 3, @QueueBinding shows how to bind a queue to an exchange.
  3. In line 4, @Queue by itself creates a random,
...