[英]Django: Postgres connection not closing
我的问题是,随着时间的推移,我的Django应用程序会积累postgres连接。 似乎每隔30分钟就会建立一个新的连接,而旧的连接不会关闭(请参见屏幕)。 由于一段时间后将最大连接数设置为100,因此所有连接均被阻止。
有谁知道是什么引起了这个问题?
我整合了一些celery tasks
后才发现这一点。 因此,我很确定这与芹菜有关。
所以我尝试在每个任务之后使用after_return
方法手动关闭连接:
from django.db import connection
class DBTask(Task):
abstract = True
def after_return(self, *args, **kwargs):
connection.close()
@task(name='example', base=DBTask)
def example_task(value):
# do some stuff
但这也无济于事。 也许我完全错了,它根本与celery
无关。
我的数据库配置:
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'production',
'USER': 'production',
'HOST': 'some.host',
'CONN_MAX_AGE': 0,
},
}
已安装的软件包:
该应用程序是在webfaction上部署的(也许有帮助)
我也看到了这个问题 ,但是设置CONN_MAX_AGE: 0
并没有帮助。
尝试在每个celery任务的末尾添加connection.close()
,但连接数量仍在增加。
尝试在celery文件顶部添加connection.close()
,但这也无济于事。
这是我在celery任务中实际使用的代码:
@task(name='push_notifications', base=DBTask)
def push_notifications_task(user_id):
user = CustomUser.objects.get(id=user_id)
PusherAPI().push_notifications(user)
connection.close()
class PusherAPI(object):
def push_notifications(self, user):
from .serializers import NotificationSerializer
self.pusher.trigger(
'user_%s' % user.slug,
'notifications',
NotificationSerializer(user).data
)
class NotificationSerializer(object):
def __init__(self, user=None):
if user is None:
self.user = get_current_user()
else:
self.user = user
@property
def data(self):
# get notifications from db
notifications = self.user.notifications.unread()
# create the notification dict
...
return note_dict
唯一的数据库查询位于CustomUser.objects.get(id=user_id)
, notifications = self.user.notifications.unread()
确保实际上是未关闭的旧连接,而不是堆积新的连接,因为您的应用程序的某些部分无法处理负载。 看一下各个连接,例如使用SELECT * FROM pg_stat_activity;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.