gpt4 book ai didi

mysql - celeryworker 24小时空闲时数据库连接错误

转载 作者:行者123 更新时间:2023-11-29 16:02:45 26 4
gpt4 key购买 nike

我有一个基于 django 的 Web 应用程序,我使用 Kafka 来处理一些订单。现在我使用 Celery Workers 为每个主题分配一个 Kafka Consumer。每个 Kafka Consumer 都以 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")

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

最佳答案

根据https://github.com/celery/django-celery-results/issues/58#issuecomment-418413369以及上面放置此代码的注释:

from django.db import close_old_connections
close_old_connections()

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

关于mysql - celeryworker 24小时空闲时数据库连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56035766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com