2013-05-22 174 views
10

我們使用amqplib來發布/使用消息。我希望能夠讀取隊列中的消息數量(最好是已確認和未確認)。這將允許我向管理員用戶顯示一個很好的狀態圖,並檢測某個組件是否跟不上負載。獲取RabbitMQ隊列中的消息數

我在amqplib文檔中找不到關於讀取隊列狀態的任何信息。

有人能指出我正確的方向嗎?

+1

檢查這個答案http://stackoverflow.com/questions/8192584/get-queue-size-in-pika-amqp-python/13629296#13629296 – mike

+0

感謝@mike,那很大程度上是我在C#中重新實現這些時所做的最終結果。對於Python方法,我結束了對rabbitmq-admin插件的訪問,並且查詢了該插件。無論如何,我很欣賞指針。 – Basic

回答

15

使用鼠:

import pika 

pika_conn_params = pika.ConnectionParameters(
    host='localhost', port=5672, 
    credentials=pika.credentials.PlainCredentials('guest', 'guest'), 
) 
connection = pika.BlockingConnection(pika_conn_params) 
channel = connection.channel() 
queue = channel.queue_declare(
    queue="your_queue", durable=True, 
    exclusive=False, auto_delete=False 
) 

print(queue.method.message_count) 

使用PyRabbit:

from pyrabbit.api import Client 
cl = Client('localhost:55672', 'guest', 'guest') 
cl.get_messages('example_vhost', 'example_queue')[0]['message_count'] 

使用HTTP

語法:

curl -i -u user:password http://localhost:15672/api/queues/vhost/queue 

例子:

curl -i -u guest:guest http://localhost:15672/api/queues/%2f/celery   

注:默認的虛擬主機是/需要被轉義爲%2f

使用CLI:

$ sudo rabbitmqctl list_queues | grep 'my_queue' 
+1

中提及PyRabbit解決方案檢索來自隊列的消息。我想你想用'cl.get_queue(「example_vhost」,「example_queue」)['messages']'來代替。 – Bill

0

使用Java API,你可以做到以下幾點:

channel.queueDeclarePassive(queueName).getMessageCount() 

我相信這也可以用amqplib(根據https://code.google.com/p/py-amqplib/source/browse/amqplib/client_0_8/channel.py#1356似乎queue_declare()返回一個元組的消息計數)

如果您需要更精確的指標(尤其是nack消息數),則需要使用rabbitmqctl或rabbitmq_management。由於其HTTP API,Rabbitmq_management可能是一個不錯的選擇。更多信息:http://www.rabbitmq.com/management.html

+2

「問題:使用Python如何...」 - 「答:使用Java你......」 - > -1 – jsbueno

+0

截至今日,'Python'沒有在OP – mkrufky

6

ChillarAnand你的答案如下可以輕鬆獲得價值。數據在對象中。

import pika 

connection = pika.BlockingConnection(pika.ConnectionParameters(
      host='localhost', 
      port=5672, 
      credentials=pika.credentials.PlainCredentials('guest', 'guest'), 
     ) 
channel = connection.channel() 
print(channel.queue_declare(queue="your_queue", durable=True, exclusive=False, 
        auto_delete=False).method.message_count) 

,你會得到確切的消息數

相關問題