【发布时间】: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")
有没有我可以在收到任务后立即检查数据库连接是否存在,如果不存在,我可以重新建立连接?
【问题讨论】:
-
@pako,所以如果我在我的任务中执行此操作,是否会自动建立新连接? #Fix temporary (2006, 'MySQL server has gone away') from django.db import close_old_connections close_old_connections()
-
没错。你也可以尝试做原始的'SELECT 1;'通过原始连接 (docs.djangoproject.com/en/2.2/topics/db/sql/…),如果发生错误,请调用 connection.connect() (stackoverflow.com/a/50694172/2156813)
-
感谢@pako,我已将此更改部署到服务器,将等到明天 ;-)
-
有任何结果吗?好还是不好? ;)
标签: mysql python-3.x apache-kafka django-celery confluent-platform