fix: 修复数据库连接没有关闭问题 (#7227)

* fix: 修复数据库连接没有关闭的bug

perf: websocket 断开也添加关闭数据库连接

* fix: 修复数据库连接没有关闭问题

Co-authored-by: ibuler <ibuler@qq.com>
This commit is contained in:
fit2bot
2021-11-18 18:47:01 +08:00
committed by GitHub
parent 6e5dcc738e
commit d2df8acd84
9 changed files with 87 additions and 35 deletions

View File

@@ -3,6 +3,7 @@ import json
from redis.exceptions import ConnectionError
from channels.generic.websocket import JsonWebsocketConsumer
from common.db.utils import close_old_connections
from common.utils import get_logger
from .site_msg import SiteMessageUtil
from .signals_handler import new_site_msg_chan
@@ -49,27 +50,40 @@ class SiteMsgWebsocket(JsonWebsocketConsumer):
self.send_unread_msg_count()
try:
for message in self.chan.listen():
msgs = self.chan.listen()
# 开始之前关闭连接因为server端可能关闭了连接而 client 还在 CONN_MAX_AGE 中
close_old_connections()
for message in msgs:
if message['type'] != 'message':
continue
try:
msg = json.loads(message['data'].decode())
logger.debug('New site msg recv, may be mine: {}'.format(msg))
if not msg:
continue
users = msg.get('users', [])
logger.debug('Message users: {}'.format(users))
if user_id in users:
self.send_unread_msg_count()
except json.JSONDecoder as e:
logger.debug('Decode json error: ', e)
continue
if not msg:
continue
logger.debug('New site msg recv, may be mine: {}'.format(msg))
users = msg.get('users', [])
logger.debug('Message users: {}'.format(users))
if user_id in users:
self.send_unread_msg_count()
except ConnectionError:
logger.debug('Redis chan closed')
logger.error('Redis chan closed')
finally:
logger.info('Notification ws thread end')
close_old_connections()
def disconnect(self, close_code):
if self.chan is not None:
try:
try:
if self.chan is not None:
self.chan.close()
except:
pass
self.close()
self.close()
finally:
close_old_connections()
logger.info('Notification websocket disconnect')