[sae] 部署了个应用, 经常遇到这个问题: MySQL server has gone away

2013-08-29 09:03:19 +08:00
 geew
在新浪sae上部署的应用,经常遇到这个错误

OperationalError: (OperationalError) (2006, 'MySQL server has gone away')

大家知道怎么回事吗?

使用了sqlalchemy, google了一下, 也改了engine了, 如下:
engine = create_engine('mysql://'+str(MYSQL_USER)+':'+str(MYSQL_PASS)+'@'+str(MYSQL_HOST)+':'+str(MYSQL_PORT)+'/'+str(MYSQL_DB)+'?charset=utf8', echo=False, pool_size=20, pool_recycle=30)

照样会遇到这个错误.
4340 次点击
所在节点    问与答
7 条回复
caoyue
2013-08-29 09:26:24 +08:00
可能是长时间没有操作请求导致连接被关闭了
设置 MySQL 的 interactove_timeout 值
或者设置 sqlalchemy 的 pool_recycle 值
geew
2013-08-29 10:13:48 +08:00
@caoyue pool_recycle=30 新浪sae的超时是30秒, 但是这样了还有问题
wzxjohn
2013-08-29 10:15:21 +08:00
SAE的mysql相当不稳定,这个问题出了很久了。淡定。
hit9
2013-08-29 11:27:30 +08:00
```
try:
cls.conn.ping() # ping to test if the connection is working
except MySQLdb.OperationalError:
cls.connect()
```

每次连接试下ping。

详见: https://github.com/hit9/CURD.py/blob/master/CURD.py#L134
luckyduck
2013-08-29 11:47:04 +08:00
这个问题在BAE上同样会有的,并不是不稳定,而是故意设计的这样一种机制,来防止MySQL产生大量的空闲链接。你可以在每次数据库操作前判断一下当前的空闲时间,如果超过30秒就重连。Tornado分出来的torndb就支持这种操作,可以设置max_idle_time。

def _ensure_connected(self):
# Mysql by default closes client connections that are idle for
# 8 hours, but the client library does not report this fact until
# you try to perform a query and it fails. Protect against this
# case by preemptively closing and reopening the connection
# if it has been idle for too long (7 hours by default).
if (self._db is None or
(time.time() - self._last_use_time > self.max_idle_time)):
self.reconnect()
self._last_use_time = time.time()
geew
2013-08-29 11:50:41 +08:00
@luckyduck sqlalchemy有类似的机制吗 pool_recycle选项貌似不起作用
luckyduck
2013-08-29 11:58:53 +08:00
@geew 你可以试试把pool_recycle设置成5,再运行一段时间看会不会还报这个错。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/80588

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX