0
0
Spring Bootframework~5 mins

RabbitTemplate for producing in Spring Boot

Choose your learning style9 modes available
Introduction

RabbitTemplate helps send messages to RabbitMQ easily. It hides complex details so you can focus on sending data.

You want to send notifications from your app to other services.
You need to queue tasks for background processing.
You want to send data updates to multiple systems asynchronously.
You want to decouple parts of your app by sending messages instead of direct calls.
Syntax
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.

Examples
Sends a simple text message "Hello World" to the exchange named "myExchange" with routing key "myRoutingKey".
Spring Boot
rabbitTemplate.convertAndSend("myExchange", "myRoutingKey", "Hello World");
Sends a LogMessage object to the "logs" exchange with routing key "info".
Spring Boot
rabbitTemplate.convertAndSend("logs", "info", new LogMessage("App started"));
Sends a message directly to a queue named "queueName" by using the default exchange (empty string).
Spring Boot
rabbitTemplate.convertAndSend("", "queueName", "Direct to queue");
Sample Program

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.

Spring Boot
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);
        };
    }
}
OutputSuccess
Important Notes

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.

Summary

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.