현제의 현재이야기

2006, 'MySQL server has gone away' 해결 기록 본문

DRF/OSOD

2006, 'MySQL server has gone away' 해결 기록

현재의 현제 2023. 4. 28. 11:11

자동 메일을 보내주는 schduler가 자꾸 6시 30분에 2006, 'MySQL server has gone away' 가 서버로그에 찍혔다.

timeout 시간을 늘리거나,, 패킷 전송 허용량을 늘리는 뻘짓을 추가하였지만 계속 6시 30분에 뻑이 갔다.

SET GLOBAL wait_timeout = 28800;

이런 것도 해보고

settings.py 에 이런 것도 추가해보고

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '3306',
        'CONN_MAX_AGE': 600, # 10 minutes
    }
}

마지막으로 그 전의 db연결을 끊고, 새롭게 db를 불러오는 django 메소드인 close_old_connections을 사용했다.

 

from apscheduler.schedulers.background import BackgroundScheduler
from django.db import close_old_connections
from .email import SubMailView


class MyScheduler:
    def __init__(self):
        self.scheduler = BackgroundScheduler(max_instances=1)
        self.job_id = 'my_job_id'
        self.sub_mail_view = SubMailView()
        self.scheduler.add_job(
            self.my_job,
            'cron',
            day_of_week='*',
            hour=6,
            minute=30,
            second=00,
            id=self.job_id
        )

    def my_job(self):
        try:
            close_old_connections()
            print('SubMailView.get() function is called.')
            self.sub_mail_view.get(request=None)
        except Exception as e:
            print(e)

그랬더니 'MySQL server has gone away'가 뜨지 않고 정상적으로 스케쥴러가 작동했다.

즉, apsheduler를 이용하려면

python manage.py runserver 0.0.0.0:8000 --noreload
from django.db import close_old_connections
close_old_connections()

이 두개를 사용하면 말끔이 해결!

Comments