基于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 各自都能消费到消息

相关推荐
IVEN_6 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang7 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮7 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling7 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮10 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽11 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
用户8307196840821 天前
RabbitMQ vs RocketMQ 事务大对决:一个在“裸奔”,一个在“开挂”?
后端·rabbitmq·rocketmq