鼠兔上下文管理器

时间:2021-02-04 07:51:42

标签: python python-3.x rabbitmq pika

我正在尝试编写一个上下文管理器来使用 pika 连接到 rabbit。这是它的样子

import pika
 
 
class RabbitConnection:
    def __init__(self, host, user, password, queue_name, port=5627):
        self.host = host
        self.user = user
        self.password = password
        self.port = port
        self.queue_name = queue_name
 
    def __enter__(self):
        credentials = pika.PlainCredentials(self.user, self.password)
        parameters = pika.ConnectionParameters(
            host=self.host,
            port=self.port,
            credentials=credentials
        )
        self.connection = pika.BlockingConnection(parameters)
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=self.queue_name)
        return self.channel
 
    def __exit__(self):
        self.connection.close()

但它不起作用。这是用于向兔子发送消息的简单 django 视图

def send_message(request):
    message = request.GET['message']
    queue_name = 'hello'
    with RabbitConnection(settings.RABBIT_HOST, settings.RABBIT_USER, settings.RABBIT_PASSWORD, queue_name) as rc:
        rc.basic_publish(
            exchange='',
            routing_key=queue_name,
            body=message,
        )
    return HttpResponse()

但我在行 pika.exceptions.AMQPConnectionError

上遇到错误 self.connection = pika.BlockingConnection(parameters)

有趣的是,当我在没有上下文管理器的情况下使用相同的代码时,它可以工作(没有错误)

def send_message(request):
    message = request.GET['message']
    queue_name = 'hello'
    credentials = pika.PlainCredentials(settings.RABBIT_USER, settings.RABBIT_PASSWORD)
    parameters = pika.ConnectionParameters(
        host=settings.RABBIT_HOST,
        port=5672,
        credentials=credentials
    )
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.queue_declare(queue='hello')
    channel.basic_publish(
        exchange='',
        routing_key='hello',
        body=message,
    )
    connection.close()
    return HttpResponse()

问题出在哪里?

1 个答案:

答案 0 :(得分:1)

查看您使用的默认端口:

def __init__(self, host, user, password, queue_name, port=5627):

rabbitmq 端口通常是 5672...