Coding a Consumer
Learn how to write a RabbitMQ consumer.
We'll cover the following...
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.
Here’s a breakdown of the code above:
-
In line 1,
@Serviceensures that an instance of this class is created when launched. -
In line 7, the
ItemRepositoryis 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:
Here’s a breakdown of the code above:
- In line 1,
@RabbitListenerinforms Spring AMQP to configure a message listener, ready to consume messages. - In line 3,
@QueueBindingshows how to bind a queue to an exchange. - In line 4,
@Queueby itself creates a random,