RabbitMQ - 如何获得队列大小

时间:2015-02-08 14:53:05

标签: python rabbitmq

我希望我的python脚本能够在将任务发送到队列之前不断运行并检查队列大小是否为零。以下是一个片段:

#!/usr/bin/env python
import pika
import sys

while True:

    # establish connection with RabbitMQ server
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()

    # create queue
    # durable=True make sure RabbitMQ never lose our queue
    rabbit_queue = channel.queue_declare(queue="task_queue", durable=True)

    queue_size = rabbit_queue.method.message_count
    if queue_size <= 0:
        message = get_message()
        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(3)

    # close connection to flush network buffers AND ensure our message was actually delivered to RabbitMQ
    connection.close()

不断重建连接是一种好习惯吗?

1 个答案:

答案 0 :(得分:0)

我认为没有理由不在while循环外打开/关闭连接:

#!/usr/bin/env python

import pika
import sys


# establish connection with RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))

try:
    channel = connection.channel()

    # create queue
    # durable=True make sure RabbitMQ never lose our queue
    channel.queue_declare(queue="task_queue", durable=True)

    while True:
        rabbit_queue = channel.queue_declare(queue="task_queue", durable=True, passive=True)
        queue_size = rabbit_queue.method.message_count
        if queue_size <= 0:
            message = get_message()
            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(3)
finally:
    connection.close()