Rabbitmq发送两个数字
时间: 2024-05-06 07:19:04 浏览: 16
可以通过RabbitMQ的生产者发送两个数字,具体操作步骤如下:
1. 首先需要安装 RabbitMQ 的 Python 客户端库 pika。
```
pip install pika
```
2. 编写生产者代码,发送两个数字。
```python
import pika
# 连接 RabbitMQ 服务器
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 创建队列
channel.queue_declare(queue='numbers')
# 发送两个数字
channel.basic_publish(exchange='', routing_key='numbers', body='1')
channel.basic_publish(exchange='', routing_key='numbers', body='2')
# 关闭连接
connection.close()
```
3. 上面代码中,我们先连接 RabbitMQ 服务器,然后创建一个名为 numbers 的队列。接着,我们分别发送数字 1 和数字 2,然后关闭连接。
4. 编写消费者代码,接收并打印这两个数字。
```python
import pika
# 连接 RabbitMQ 服务器
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 创建队列
channel.queue_declare(queue='numbers')
def callback(ch, method, properties, body):
print("Received:", body.decode())
# 接收消息
channel.basic_consume(queue='numbers', on_message_callback=callback, auto_ack=True)
# 开始接收消息
channel.start_consuming()
```
5. 上面代码中,我们先连接 RabbitMQ 服务器,然后创建一个名为 numbers 的队列。接着,定义一个回调函数 callback,用于接收消息。最后,我们开始接收消息并打印出来。
6. 运行消费者代码,我们可以看到如下输出:
```
Received: 1
Received: 2
```
这样,我们就成功使用 RabbitMQ 发送了两个数字。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)