消息队列生产者和消费者代码
时间: 2024-11-29 21:15:10 浏览: 4
消息队列是一种常见的分布式系统通信模式,其中生产者负责生成数据或消息,而消费者则接收并处理这些消息。下面是一个简单的Python示例,使用了`pika`库来演示AMQP(Advanced Message Queuing Protocol)风格的消息队列:
```python
# 导入必要的库
import pika
# 生产者代码
def producer():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明交换机和队列
channel.exchange_declare(exchange='test_exchange', exchange_type='direct')
queue_name = 'my_queue'
channel.queue_declare(queue=queue_name)
# 将消息发送到队列
message = "Hello World!"
channel.basic_publish(exchange='test_exchange', routing_key=queue_name, body=message)
print(f" [x] Sent {message}")
# 关闭连接
connection.close()
print(" [x] Done")
# 消费者代码
def consumer():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明自动应答队列
channel.basic_qos(prefetch_count=1) # 阻塞直到下一个消息可用
channel.basic_consume(queue='my_queue', on_message_callback=on_message)
# 开始消费
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
def on_message(ch, method, properties, body):
print(f" [x] Received {body}")
ch.basic_ack(delivery_tag = method.delivery_tag) # 确认收到消息
if __name__ == "__main__":
producer()
consumer()
```
在这个例子中,生产者创建了一个消息,并将其发送到名为'my_queue'的队列;消费者从这个队列中取出并处理消息。运行这个程序,你可以看到生产者发送消息,然后消费者接收并打印出来。
阅读全文