基于python 开发调试rabbitmq - 2

基于python 3 pika 调试 openstack rabbitmq

创建工作队列,类比一个大的工作,需要发送多个小任务到队列中,让多个消费者消费

多个任务时,多个消费者消费任务

new_task.py

复制代码
#!/usr/bin/env python
import pika
import sys

credentials = pika.PlainCredentials('openstack', 'servicepasswd')
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='10.146.203.171',virtual_host='/',credentials=credentials))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)

message = ' '.join(sys.argv[1:]) or "Hello World!"
channel.basic_publish(
    exchange='',
    routing_key='task_queue',
    body=message,
    properties=pika.BasicProperties(
        delivery_mode=pika.DeliveryMode.Persistent
    ))
print(f" [x] Sent {message}")
connection.close()

worker1.py

复制代码
#!/usr/bin/env python
import pika
import time

credentials = pika.PlainCredentials('openstack', 'servicepasswd')
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='10.146.203.171',virtual_host='/',credentials=credentials))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)
print(' [*] Waiting for messages. To exit press CTRL+C')


def callback(ch, method, properties, body):
    print(f" [x] Received {body.decode()}")
    time.sleep(body.count(b'.'))
    print(" [x] Done")
    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_qos(prefetch_count=1)  #qos  限制,公平分发
channel.basic_consume(queue='task_queue', on_message_callback=callback)

channel.start_consuming()

worker2.py

代码同 复制代码
代码同worker1

当多次执行new_task.py 时,模拟发送了多个任务出去,此时 worker1和worker2 各自都能消费到消息

相关推荐
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时1 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1231 天前
2026年第38周GitHub趋势周报
python·科技·github