[英]Django/Docker-compose: Retry Database Connection when: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
This question have been asked here: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") and the answer has been to wait for the database to be ready.这里已经问过这个问题: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")答案是等待数据库准备好。
However, the official documentation here: https://docs.docker.com/compose/startup-order/ suggests that instead an in app retry method is implemented in order to retry the database connection when this fails.但是,此处的官方文档: https : //docs.docker.com/compose/startup-order/建议实现应用程序内重试方法,以便在失败时重试数据库连接。
To handle this, design your application to attempt to re-establish a connection to the database after a failure.
要处理此问题,请将您的应用程序设计为在失败后尝试重新建立与数据库的连接。 If the application retries the connection, it can eventually connect to the database.
如果应用程序重试连接,它最终可以连接到数据库。
The best solution is to perform this check in your application code, both at startup and whenever a connection is lost for any reason.
最好的解决方案是在您的应用程序代码中执行此检查,无论是在启动时还是在由于任何原因丢失连接时。
Unfortunately, the documentation just ends there and does not provide any examples or guides on how to implement this retry method.不幸的是,文档就到此为止,并未提供有关如何实现此重试方法的任何示例或指南。 Does anyone knows how to do that in a clean way?
有谁知道如何以干净的方式做到这一点?
Restart django cassandra conection in manage.py在 manage.py 中重新启动 django cassandra 连接
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import logging
import os
import sys
from time import sleep
from cassandra.cluster import NoHostAvailable
from django.core.management import execute_from_command_line
MAX_RETRIES_NUM = 10
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings')
try:
from django.core.management.commands.runserver import Command
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
from django.db import connections
conn = connections['default']
no_host_available = True
retry_count = 0
sleep_time = 1
while no_host_available:
try:
conn.connect()
except NoHostAvailable:
if retry_count == MAX_RETRIES_NUM:
sys.exit()
logging.warning(f'Error de conexión con la base de datos. Reintentando conexión en {sleep_time}s')
sleep(sleep_time)
else:
no_host_available = False
sleep_time *= 1.5
retry_count += 1
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.