RabbitTemplate helps send messages to RabbitMQ easily. It hides complex details so you can focus on sending data.
RabbitTemplate for producing in Spring Boot
rabbitTemplate.convertAndSend(exchange, routingKey, message);
exchange: The name of the RabbitMQ exchange to send the message to.
routingKey: The key used to route the message to the correct queue.
rabbitTemplate.convertAndSend("myExchange", "myRoutingKey", "Hello World");
rabbitTemplate.convertAndSend("logs", "info", new LogMessage("App started"));
rabbitTemplate.convertAndSend("", "queueName", "Direct to queue");
This Spring Boot app sends a simple text message to RabbitMQ when it starts. It uses RabbitTemplate's convertAndSend method to send the message to the specified exchange and routing key.
import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class RabbitProducerApp { public static void main(String[] args) { SpringApplication.run(RabbitProducerApp.class, args); } @Bean CommandLineRunner sendMessage(RabbitTemplate rabbitTemplate) { return args -> { String exchange = "myExchange"; String routingKey = "myRoutingKey"; String message = "Hello RabbitMQ!"; rabbitTemplate.convertAndSend(exchange, routingKey, message); System.out.println("Message sent: " + message); }; } }
Make sure RabbitMQ server is running and the exchange exists before sending messages.
You can send any object as a message if it is serializable or has a converter configured.
Use the default exchange (empty string) to send messages directly to a queue by naming the queue as the routing key.
RabbitTemplate simplifies sending messages to RabbitMQ.
Use convertAndSend with exchange, routing key, and message.
It helps decouple your app by using messaging instead of direct calls.