rabbitmq demo
时间: 2023-07-06 10:40:13 浏览: 56
好的,这里是一个 RabbitMQ 的 demo,使用 Python 编写:
首先,需要安装 pika 库,可以使用以下命令进行安装:
```
pip install pika
```
然后,我们需要编写两个脚本,一个用于发送消息,一个用于接收消息。
发送消息的脚本:
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
```
接收消息的脚本:
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
channel.basic_consume(queue='hello',
on_message_callback=callback,
auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
```
运行接收消息的脚本后,再运行发送消息的脚本,就可以在控制台看到接收到的消息了。