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