如何为Python编写的RabbitMQ发送端开发Spring Boot消费端?
Got it, let's build a full working setup where your Python script sends messages to RabbitMQ via a topic exchange, and a Spring Boot app consumes those messages. I'll fill in the missing parts of your sender code and walk through the consumer side too.
Python Producer (sender.py)
First, let's fix and complete your sender script—it looks like it got truncated. Here's the full, functional version:
#!/usr/bin/env python import pika import sys # Establish connection to local RabbitMQ server connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() # Declare a topic-type exchange (topic exchanges route messages based on routing key patterns) channel.exchange_declare(exchange='topic_logs', exchange_type='topic') # Get routing key from command line args, default to 'anonymous.info' if not provided routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info' # Get message content from args, default to 'Hello World!' message = ' '.join(sys.argv[2:]) or 'Hello World!' # Publish the message to the topic exchange with the specified routing key channel.basic_publish( exchange='topic_logs', routing_key=routing_key, body=message.encode('utf-8') ) print(f" [x] Sent '{routing_key}':'{message}'") connection.close()
Quick Explanation:
- We connect to RabbitMQ running on
localhost(adjust the host if your RabbitMQ is on a remote server) - The
topic_logsexchange is declared astopictype—this lets us use wildcard patterns in routing keys (like*.info,user.#) - Routing key and message are taken from command line arguments for flexibility (e.g., run
python sender.py user.login "User Alice logged in"to send a message with routing keyuser.login)
Spring Boot Consumer
Now let's set up the Spring Boot app to consume these messages.
1. Add RabbitMQ Dependency (Maven)
Add this to your pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
2. RabbitMQ Configuration (application.yml)
Add these settings to your application.yml (or application.properties):
spring: rabbitmq: host: localhost port: 5672 username: guest password: guest # default credentials, change if you've modified RabbitMQ settings
3. Declare Exchange, Queue, and Binding
Create a configuration class to set up the topic exchange, a queue, and bind them with a routing pattern:
import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitMQConfig { public static final String TOPIC_EXCHANGE_NAME = "topic_logs"; public static final String QUEUE_NAME = "app_log_queue"; // Declare the topic exchange @Bean public TopicExchange topicExchange() { return new TopicExchange(TOPIC_EXCHANGE_NAME); } // Declare the queue to consume messages @Bean public Queue appLogQueue() { return new Queue(QUEUE_NAME, false); // non-durable queue } // Bind the queue to the exchange with a routing pattern (e.g., listen to all *.info messages) @Bean public Binding binding(Queue appLogQueue, TopicExchange topicExchange) { return BindingBuilder.bind(appLogQueue).to(topicExchange).with("*.info"); // adjust pattern as needed } }
4. Consumer Listener Class
Create a listener to handle incoming messages:
import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MessageConsumer { @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME) public void receiveMessage(String message) { System.out.println(" [x] Received message: " + message); // Add your business logic here to process the message } }
Testing the Setup
- Make sure RabbitMQ is running locally (start it via
rabbitmq-servercommand or Docker) - Run the Spring Boot app—it will connect to RabbitMQ and start listening to the queue
- Run the Python sender script with different routing keys:
python sender.py system.info "Server started successfully"python sender.py user.info "User Bob registered"python sender.py user.warning "Invalid login attempt"
The Spring Boot app will receive messages where the routing key matches the *.info pattern we set in the binding.
内容的提问来源于stack exchange,提问作者megna

