rabbitmq pika常用方法
时间: 2023-09-22 18:11:48 浏览: 169
erlang+rabbitmq.zip
1.连接到RabbitMQ服务器
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
```
2.声明队列
```python
channel.queue_declare(queue='hello')
```
3.发送消息
```python
channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
```
4.消费消息
```python
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
```
5.启动消费者
```python
channel.start_consuming()
```
6.关闭连接
```python
connection.close()
```
阅读全文