python连接rabbitmq

rabbitmq官方python连接

具体还是看官方文档,这是一个小demo接受脚本

import pika

class queue():
    def __init__(self):
        self.MQ_CONFIG = {
            "host": "***.**.***.***",
            "port": '5672',    #注意default是5672,ip地址上的端口15672,去掉1
            "vhost": "***",    #vhost需要保持一致
            "user": "***",
            "passwd": "******"
        }

    def connet(self):
        credentials = pika.PlainCredentials(self.MQ_CONFIG.get("user"), self.MQ_CONFIG.get("passwd"))
        parameters = pika.ConnectionParameters(self.MQ_CONFIG.get("host"), self.MQ_CONFIG.get("port"),
                                               self.MQ_CONFIG.get("vhost"),
                                               credentials)
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()

        l_ecom_item_key = []
        # 我这里使用的是接受一定的数量,然后关闭,但是这种方法会导致队列消息清空
        # 或者把这里的auto_ack=True改成False,队列消息不清空
        def callback(ch, method, properties, body):
            print(body)
            l_ecom_item_key.append(body)
            if len(l_ecom_item_key) == 3:
                connection.close()
        channel.basic_consume(queue='q_test_01', on_message_callback=callback, auto_ack=True)  # DEFAULT: auto_ack=True
        channel.start_consuming()
        return l_ecom_item_key

# return a list of ecom_item_key

# que = queue()
# l_ecom_item_key = que.connet()

 

你可能感兴趣的:(rabbitmq)