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

相关推荐
Warson_L14 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅14 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅14 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L14 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅15 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L15 小时前
python的类&继承
python
Warson_L15 小时前
类型标注/type annotation
python
ThreeS18 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵19 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏