RabbitTemplate is Spring’s API for sending messages to and pulling messages from RabbitMQ. Spring Boot creates a RabbitTemplate bean when you add the AMQP starter, so an application service can receive it through constructor injection. section 9.2.1 section 9.2.2
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
Add this dependency before injecting RabbitTemplate. The application also needs access to a RabbitMQ broker. section 9.2.1
For sending, call send() with a raw Message, or call convertAndSend() with an object that should be converted before it goes to the broker. Sending can specify an exchange and routing key; omitted values use defaults. These methods are defined by AmqpTemplate, which RabbitTemplate implements. section 9.2.2
Send an order
An order service can call rabbit.convertAndSend("tacocloud.order", order) after configuring the template’s exchange as tacocloud.order and routing key as kitchens.central. For more control, it can obtain rabbit.getMessageConverter(), turn the order into a Message, set an X_ORDER_SOURCE header in its MessageProperties, and call send(). A MessagePostProcessor offers another way to change the converted message before sending. section 9.2.2
For receiving, call receive() to pull a raw Message from a queue, or receiveAndConvert() to get a converted object. The consumer names a queue—not an exchange or routing key—because routing has already placed the message there. The default receive timeout is zero milliseconds, so a pull can return immediately with null. A timeout can make it wait, but null remains possible. section 9.2.3
Pull an order
A kitchen receiver can call rabbit.receive("tacocloud.order.queue", 30000), check for null, and use rabbit.getMessageConverter().fromMessage(message) to recover the order. To avoid manual conversion, it can instead call receiveAndConvert() with the queue name. For push-based delivery rather than pulling, a method annotated @RabbitListener can receive orders. section 9.2.3
