標籤:
RabbitMQ(一) -- Work Queues
RabbitMQ使用Work Queues的主要目的是為了避免資源使用密集的任務,它不同於定時任務處理的方式,而是把任務封裝為訊息添加到隊列中。而訊息佇列正是共用於多個工作者中使用,它們可以隨意pop出資料進行處理。
訊息的持久化 Message durability
為了保證`rabbitmq`意外重啟等原因造成的訊息丟失,通過設定訊息的durable來實現資料的持久化,但是需要生產者和消費者同時設定持久化才會生效。
需要注意的是,`rabbitmq`並不允許更改已經建立的訊息佇列的屬性,假如之前已經建立過非持久化的hello訊息佇列,那麼會返回一個錯誤資訊。
設定訊息佇列的可持久化屬性(第二個參數):
channel.queue_declare(queue=‘hello‘, durable=True)
在訊息發送時,需要指定`delivery_mode`來實現訊息持久化:
channel.basic_publish(exchange=‘‘, routing_key="task_queue", body=message, properties=pika.BasicProperties(delivery_mode = 2, # make message persistent))
平均分配 Fair dispatch
`rabbitmq`實現了訊息均分的功能,通過設定`basic.qos`方法的`prefetch_count`來實現。它會告訴`rabbitmq`的生產者不要給一個消費者分配過多的任務,也就是說不要在消費者處理完成已經接收到的任務之前分配新的任務。
channel.basic_qos(prefetch_count=1)
其中prefetch_count為可以接受處理的任務個數,如果未達到上限rabbitmq會繼續向消費者推送任務。
執行個體生產者
#!/usr/bin/env python# coding=utf-8import pikaimport timeconnection = pika.BlockingConnection(pika.ConnectionParameters(host=‘localhost‘))channel = connection.channel()channel.queue_declare(queue=‘task_queue‘, durable=True)for i in range(100): message = str(i) + ‘ Hello World!‘ channel.basic_publish(exchange=‘‘, routing_key=‘task_queue‘, body=message, properties=pika.BasicProperties(delivery_mode = 2, # make message persistent)) print " [x] Sent %r" % (message,) time.sleep(1)connection.close()
消費者
#!/usr/bin/env python# coding=utf-8import pikaimport timeconnection = pika.BlockingConnection(pika.ConnectionParameters(host=‘localhost‘))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 " [x] Received %r" % (body,) time.sleep(2) print " [x] Done" ch.basic_ack(delivery_tag = method.delivery_tag)channel.basic_qos(prefetch_count=1)channel.basic_consume(callback, queue=‘task_queue‘)channel.start_consuming()
RabbitMQ(一) -- Work Queues