2
2

More than 5 years have passed since last update.

RabbitMQ Management WebAPIを使ってキューの内容を見る

Last updated at Posted at 2016-02-19

概要

サービス上で現在のキューの状況を表示するために、キューの内容を「のぞき見」したいなーと思ったのが動機です。

AMQPブローカーであるRabbitMQのキューの内容を確認するためにWebAPI経由で取得します。それだけならpika.basic_consume()やpika.consume()で取得できるのですが、他のConsumerに影響しないようにするためにManagement APIを使用します。

注意

RabbitMQのHTTP APIのドキュメントを見てみると、getの項目に、

Please note that the get path in the HTTP API is intended for diagnostics etc - it does not implement reliable delivery and so should be treated as a sysadmin's tool rather than a general API for messaging.

と書いてあるのでちょっと微妙かも

動作確認

動作確認は以下で行いました。

  • CentOS 6.7
  • Python 2.6.6 (CentOS標準)
  • RabbitMQ 3.6.0 (RabbitMQサイトのRPMおよびErlang solutionsのリポジトリ)

準備

Management Pluginを有効にする

RabbitMQ Management Pluginを有効にしておく必要があります。

sudo rabbitmq-plugins enable rabbitmq_management

キューにメッセージをためておく

確認のため、キューにメッセージを送ります。

publish.py
#!/usr/bin/env python
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters())
ch = conn.channel()
ch.queue_declare(queue="hello")
ch.basic_publish(exchange="", routing_key="hello", body="Message 1")
ch.basic_publish(exchange="", routing_key="hello", body="Message 2")
conn.close()

WebAPIで取得

httplibを使って取得するだけです。

view_messages.py
from base64 import b64encode
import httplib, json

API_HOST = "localhost"  # 接続先ホスト名
API_PORT = 15672        # 接続ポート

def view_messages(vhost, queue, count=1):
    # URI等の組み立て
    uri = "/queues/%(vhost)s/%(queue)s/get" % {"vhost": vhost, "queue": queue}
    auth = "guest:guest"
    headers = {
        "Authorization" : "Basic %s" % b64encode(auth),
        "Content-Type"  : "application/json",
    }
    opt = {"count": count, "requeue": "true", "payload_file": None, "encoding": "auto"}

    # RabbitMQ Managementに接続してメッセージを取得
    conn = httplib.HTTPConnection(API_HOST, API_PORT)
    body = json.dumps(opt)
    conn.request("POST", "/api%s" % uri, body, headers)
    response = conn.getresponse()
    return json.loads(response.read())

if __name__ == "__main__":
    msgs = view_messages("%2F", "hello", count=100)
    for msg in msgs:
        print msg["payload"]

ためしてみる

試してみます。

./publish.py
./view_messages.py
Message 1
Message 2

リファレンス

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2