您的位置:首页 > 健康 > 美食 > 基于python 开发调试rabbitmq - 2

基于python 开发调试rabbitmq - 2

2024/12/28 0:48:16 来源:https://blog.csdn.net/u010494323/article/details/141184594  浏览:    关键词:基于python 开发调试rabbitmq - 2

基于python 3 pika 调试 openstack rabbitmq

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

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

new_task.py

#!/usr/bin/env python
import pika
import syscredentials = 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 timecredentials = 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 各自都能消费到消息

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com