如何重新连接消费者与扭曲连接为鼠兔?

2024-04-24 14:13:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pika twisted connection作为RabbitMQ消费者,下面是我的代码:

@defer.inlineCallbacks
def run(connection):
    queue_name = 'aaa'
    channel = yield connection.channel()
    queue = yield channel.queue_declare(queue=queue_name, auto_delete=False, exclusive=False)
    yield channel.queue_bind(exchange='amq.direct',queue=queue_name,routing_key=queue_name)
    yield channel.basic_qos(prefetch_count=1)
    queue_object, consumer_tag = yield channel.basic_consume(queue=queue_name,no_ack=False)
    logger.info('[room server]start consume queue %s', queue_name)

    l = task.LoopingCall(read, queue_object)
    l.start(0.1)


@defer.inlineCallbacks
def read(queue_object):
    ch,method,properties,body = yield queue_object.get()
    try:
        data = json.loads(body)
        head_code = data['head_code']
        openid = data['openid']
        message_content = data['message_content']
        conn_id = -1
        try:
            conn_id = data['conn_id']
        except:
            pass
        message_dispatcher(head_code, openid, message_content, conn_id)
        yield ch.basic_ack(delivery_tag=method.delivery_tag)
    except ValueError as e:
        logger.error('[error!]error body %s' % body)
        yield ch.basic_ack(delivery_tag=method.delivery_tag)

credentials = pika.PlainCredentials(config.RABBITMQ_USERNAME, config.RABBITMQ_PASSWD)
parameters = pika.ConnectionParameters(credentials=credentials)
cc = protocol.ClientCreator(reactor, twisted_connection.TwistedProtocolConnection, parameters)

def got_error(failure, d):
    logger.error(failure)
    d = cc.connectTCP(config.RABBITMQ_HOST, config.RABBITMQ_PORT)


def start():
    d = cc.connectTCP(config.RABBITMQ_HOST, config.RABBITMQ_PORT)
    d.addCallback(lambda protocol: protocol.ready)
    d.addCallback(run)
    d.addErrback(got_error, d)

我的问题是当连接断开时,重新连接过程不起作用:enter image description here

如何使重新连接工作?在


Tags: nameconfigmessagedataobjectbasicqueuedef
1条回答
网友
1楼 · 发布于 2024-04-24 14:13:16

根据^{} docstring,可以提供一个on_close_callback函数来处理连接终止。在此函数中,^{} and ^{}必须是参数。因此,创建另一个on_close回调,在这里您可以处理连接终止及其发生的原因,然后执行必要的逻辑来连接到RabbitMQ:

def connection_termination(reason_code, reason_text):
    """
    Log the reasons why the connection terminates and then reconnect
    """
    # put your connection code here
    # incrementally space out your reconnections, eg. 2 seconds, if fail, 5 seconds, if fail 10 seconds, etc...

一旦完成了该代码,则ClientCreator代码应遵循以下示例:

^{pr2}$

不幸的是,我现在不能测试这个,但它应该可以工作。你已经有了大部分的逻辑,所以我把剩下的留给你做练习;)如果你有任何问题请评论,如果你有解决方案,请给其他人展示最终结果。在

相关问题 更多 >