rabbitMQ basicGet
时间: 2024-01-18 19:16:48 浏览: 27
`basicGet`是RabbitMQ中的一个API,用于从队列中获取单个消息。它的语法如下:
```python
method_frame, header_frame, body = channel.basic_get(queue='queue_name', auto_ack=True)
```
其中,`queue`参数指定要获取消息的队列名称,`auto_ack`参数指定是否自动确认消息。如果`auto_ack`为`True`,则获取到消息后会自动将其从队列中删除,否则需要手动确认。
以下是一个示例代码,演示如何使用`basicGet`从队列中获取消息:
```python
import pika
# 连接到RabbitMQ服务器
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明一个队列
channel.queue_declare(queue='hello')
# 发送一条消息
channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
# 从队列中获取消息
method_frame, header_frame, body = channel.basic_get(queue='hello', auto_ack=True)
if body:
print("Received message:", body.decode())
else:
print("No message in queue")
# 关闭连接
connection.close()
```