Spring Boot RabbitMQ:收发端最小配置与跨语言生产消费注解配置咨询
Hey there! Let's break down your questions one by one to make this clear for you as a Spring Boot RabbitMQ beginner.
You don't need a ton of setup to get started—here's the bare minimum for each side:
Producer Side Minimum Setup
- First, add the Spring Boot AMQP starter dependency to your project:
For Maven (pom.xml):
For Gradle (<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>build.gradle):implementation 'org.springframework.boot:spring-boot-starter-amqp' - Then, add basic RabbitMQ connection details to your
application.properties(orapplication.yml):
With that, you can inject the auto-configuredspring.rabbitmq.host=your-rabbitmq-server-address spring.rabbitmq.port=5672 # default RabbitMQ port, adjust if yours is different spring.rabbitmq.username=your-rabbitmq-username spring.rabbitmq.password=your-rabbitmq-passwordRabbitTemplateinto any component to start sending messages.
Consumer Side Minimum Setup
- Same dependency as the producer (
spring-boot-starter-amqp) - Same connection properties in
application.properties/application.yml - Just add a component class with a method marked by
@RabbitListener, specifying the queue you want to listen to. Spring Boot will automatically set up the listener for you:
Note: If the queue doesn't exist yet, RabbitMQ will create it automatically when the first message is sent or the listener connects (depending on your setup).@Component public class BasicConsumer { @RabbitListener(queues = "your-queue-name") public void handleMessage(String message) { System.out.println("Got message: " + message); } }
First, let's clear up your confusion about separate producer/consumer configs: Spring Boot uses auto-configuration to handle most of the AMQP boilerplate for you. Unlike XML where you had to explicitly define producers and consumers, here you just use specific components/annotations to fill those roles:
- Producers rely on the auto-configured
RabbitTemplateto send messages. - Consumers use
@RabbitListenerto mark message-handling methods.
Let's walk through cross-language examples:
Example 1: Spring Boot Producer + Python Consumer
Spring Boot Producer Code
Create a service class to handle message sending:
import org.springframework.amqp.core.AmqpTemplate; import org.springframework.stereotype.Service; @Service public class SpringProducer { private final AmqpTemplate rabbitTemplate; // Constructor injection (preferred over @Autowired) public SpringProducer(AmqpTemplate rabbitTemplate) { this.rabbitTemplate = rabbitTemplate; } public void sendGreeting(String name) { String message = "Hello, " + name + "!"; // Send to a queue named "greeting-queue" rabbitTemplate.convertAndSend("greeting-queue", message); } }
You can call this service from a controller, command-line runner, or any other component to send messages.
Python Consumer Code (using pika library)
First install pika via pip: pip install pika
import pika def consume_messages(): # Establish connection to RabbitMQ connection = pika.BlockingConnection( pika.ConnectionParameters( host="your-rabbitmq-server-address", port=5672, credentials=pika.PlainCredentials("your-username", "your-password") ) ) channel = connection.channel() # Declare the queue (matches the Spring Boot producer's queue name) channel.queue_declare(queue="greeting-queue") # Define message handler def message_callback(ch, method, properties, body): print(f"Received from Spring Boot: {body.decode()}") # Start consuming messages channel.basic_consume(queue="greeting-queue", on_message_callback=message_callback, auto_ack=True) print("Waiting for messages... Press Ctrl+C to exit") channel.start_consuming() if __name__ == "__main__": try: consume_messages() except KeyboardInterrupt: print("Stopped consumer")
Example 2: Spring Boot Consumer + Python Producer
Spring Boot Consumer Code
Create a listener component to process incoming messages:
import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class SpringConsumer { @RabbitListener(queues = "data-queue") public void processData(String data) { System.out.println("Processed data from Python: " + data); // Add your business logic here } }
When your Spring Boot app starts, it will automatically start listening to the data-queue.
Python Producer Code (using pika)
import pika def send_data(): connection = pika.BlockingConnection( pika.ConnectionParameters( host="your-rabbitmq-server-address", port=5672, credentials=pika.PlainCredentials("your-username", "your-password") ) ) channel = connection.channel() # Declare the queue (matches the Spring Boot consumer's queue name) channel.queue_declare(queue="data-queue") # Send a test message message = "Sample data from Python producer" channel.basic_publish(exchange="", routing_key="data-queue", body=message) print(f"Sent message to Spring Boot: {message}") connection.close() if __name__ == "__main__": send_data()
Key Tips for Cross-Language Success
- Ensure both sides use identical queue names, connection credentials, and message formats (we used plain text here; if you send JSON, make sure both sides can serialize/deserialize it correctly).
- If you use custom exchanges or routing keys, configure them the same way on both ends (e.g., a direct exchange with the same routing key).
内容的提问来源于stack exchange,提问作者megna




