无法收听RabbitMQ消息

时间:2018-10-17 09:25:59

标签: python-3.x rabbitmq pika python-pika

在我的项目中,我正在访问API服务并期望通过RabbitMQ发出消息。
我正在使用Python的行为框架进行测试。
我正在连接RabbitMQ。创建队列,与交换绑定队列。

import pika
import logging

#logging.basicConfig(logging.INFO)
logging.basicConfig(level=logging.INFO)

#binding_keys = "TestTopic"
#_queue_name = None
#channel = None
class Rabbitmq(object):
    EXCHANGE_TYPE = "topic"
    BINDING_KEYS = "TestTopic"
    queue_state=None
    queue_empty=None
    queue_name=None

    def create_connection(test):
        logging.info("Started create_connection method")
        global queue_empty, queue_state,queue_name
        credentials = pika.PlainCredentials("USERNAME", "USERNAME")
        parameters = pika.ConnectionParameters(host="HOST", port=PORT, credentials=credentials,virtual_host="virtual host")

        # establish connection
        connection = pika.BlockingConnection(parameters)
        global channel

        channel = connection.channel()
        channel.confirm_delivery()

        # declare exchange
        channel.exchange_declare(exchange="EXCHANGE_NAME",exchange_type="topic",durable=True)

        #declare queue
        result = channel.queue_declare(queue='QUEUE_NAME')

        queue_name = result.method.queue

        channel.queue_bind(exchange="EXCHANGE_NAME",
                               queue="QUEUE_NAME",
                               routing_key=Rabbitmq.BINDING_KEYS)
        logging.info("Ending create_connection method")


    def getMessage(self):
        logging.info("Starting getMessage")
        global channel,queue_state,queue_empty,queue_name

        logging.info("before callback method")


        def callback(ch, method, properties, body):
            print("listening [x] %r:%r" % (method.routing_key, body))
            logging.info(" [x] %r:%r" % (method.routing_key, body))


        channel.basic_consume(callback,queue="test_result_pdp_queue")
        logging.info("After basic_consume method")
        #logging.info(channel)
        channel.start_consuming()
        logging.info("After start_consuming")

在开始执行测试之前,我要调用create_connection方法,该方法将建立连接,声明交换和队列。
然后,我点击了API服务,并期望通过RabbitMQ收到一条消息,在此我调用消耗函数来消耗消息。但是我没有收到任何消息。任何帮助将不胜感激。

0 个答案:

没有答案