【问题标题】:Database connection error while celery worker remains idle for 24 hourscelery worker 闲置 24 小时时数据库连接错误
【发布时间】:2019-09-25 21:26:54
【问题描述】:

我有一个基于 django 的 Web 应用程序,我在其中使用 Kafka 来处理一些订单。现在我使用 Celery Workers 为每个主题分配一个 Kafka Consumer。每个 Kafka 消费者都以 Kafka 任务的形式分配给一个 Kafka 主题。但是大约一天后,当我提交任务时,我收到以下错误:

    _mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')

The above exception was the direct cause of the following exception:

下面是我的 tasks.py 文件的样子:

@shared_task
def init_kafka_consumer(topic):
    try:
        if topic is None:
            raise Exception("Topic is none, unable to initialize kafka consumer")
        logger.info("Spawning new task to subscribe to topic")
        params = []
        params.append(topic)
        background_thread = Thread(target=sunscribe_consumer, args=params)
        background_thread.start()
    except Exception :
        logger.exception("An exception occurred while reading message from kafka")

def sunscribe_consumer(topic) :
    try:
        if topic is None:
            raise Exception("Topic is none, unable to initialize kafka consumer")
        conf = {'bootstrap.servers': "localhost:9092", 'group.id': 'test', 'session.timeout.ms': 6000,
                'auto.offset.reset': 'earliest'}
        c = Consumer(conf)
        logger.info("Subscribing consumer to topic "+str(topic[0]))
        c.subscribe(topic)
        # Read messages from Kafka
        try:
            while True:
                msg = c.poll(timeout=1.0)
                if msg is None:
                    continue
                if msg.error():
                    raise KafkaException(msg.error())
                else:
                    try:
                        objs = serializers.deserialize("json", msg.value())
                        for obj in objs:
                            order = obj.object
                            order = BuyOrder.objects.get(id=order.id) #Getting an error while accessing DB
                            if order.is_pushed_to_kafka :
                                return
                            order.is_pushed_to_kafka = True
                            order.save()
                            from web3 import HTTPProvider, Web3, exceptions
                            w3 = Web3(HTTPProvider(INFURA_MAIN_NET_ETH_URL))
                            processBuyerPayout(order,w3)
                    except Exception :
                        logger.exception("An exception occurred while de-serializing message")
        except Exception :
            logger.exception("An exception occurred while reading message from kafka")
        finally:
            c.close()
    except Exception :
        logger.exception("An exception occurred while reading message from kafka")

有没有我可以在收到任务后立即检查数据库连接是否存在,如果不存在,我可以重新建立连接?

【问题讨论】:

标签: mysql python-3.x apache-kafka django-celery confluent-platform


【解决方案1】:

根据https://github.com/celery/django-celery-results/issues/58#issuecomment-418413369 和 cmets 把这段代码放在上面:

from django.db import close_old_connections
close_old_connections()

关闭旧连接并在任务中打开新连接应该会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-01-09
    • 2017-07-07
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多