RabbitMQ(一) -- Work Queues

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.