python pika简单实现RabbitMQ通信
2024-08-24 06:32:20
Windows上安装及启动RabbitMQ
https://blog.csdn.net/hzw19920329/article/details/53156015
安装python pika库
pip install pika
编写发送消息client.py
# coding:utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) # 创建一个连接
channel = connection.channel() # 创建通道
channel.queue_declare(queue='hello') # 把消息队列的名字为hello
channel.basic_publish(exchange='',
routing_key='hello',
body='hello world!') # 设置routing_key(消息队列的名称)和body(发送的内容)
print(" [x] sent 'Hello World!'")
connection.close() # 关闭连接
编写监听消息队列server.py
# coding:utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) # 创建一个连接
channel = connection.channel() # 建立通道
channel.queue_declare(queue='hello') # 把消费者和queue绑定起来,生产者和queue的也是hello def callback(ch, method, properties, body): # 回调函数get消息体
print(" [x] Received %r" % body) channel.basic_consume(callback,
queue='hello',
no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() # 创建死循环,监听消息队列,可使用CTRL+C结束监听
执行server.py可以监听消息队列,执行client.py启动客户端向消息队列发送消息。
最新文章
- Java代码块
- 锋利的jQuery-4--animate()的用法
- Unity Camera属性
- POJ2001Shortest Prefixes(字典树)
- Android 通过广播启动另一个应用的Activity
- *[hackerrank]Tree Covering
- mac安装GNU命令行工具
- SQLite学习网址
- [转载 java 技术栈] eclipse 阅读跟踪 Java 源码的几个小技巧!
- Spring Boot Actuator 使用
- npm install报错node-sass
- arcgis-tomcat-cors
- springboot 针对jackson是自动化配置
- Oracle之带参存储过程(存储过程中for循环调用存储过程)
- 【基本功】深入剖析Swift性能优化
- ‘,’之后要留空格,如 Function(x, y, z)
- angular中$location读取url信息
- php中 curl模拟post发送json并接收json(转)
- xxxxxxclub系统模块分类
- VirtualBox修改现有虚拟磁盘大小