鼠兔上下文管理器

pika Context Manager

我正在尝试编写上下文管理器以使用 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()

但是没有用。这是向 rabbit

发送消息的简单 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()

但是我在第 self.connection = pika.BlockingConnection(parameters)

行收到一个错误 pika.exceptions.AMQPConnectionError

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

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()

问题出在哪里?

查看您使用的默认端口:

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

rabbitmq 端口通常为 5672...