V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
geew
V2EX  ›  问与答

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

  •  
  •   geew · 2013-08-29 09:03:19 +08:00 · 4331 次点击
    这是一个创建于 3921 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在新浪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)

    照样会遇到这个错误.
    7 条回复    1970-01-01 08:00:00 +08:00
    caoyue
        1
    caoyue  
       2013-08-29 09:26:24 +08:00
    可能是长时间没有操作请求导致连接被关闭了
    设置 MySQL 的 interactove_timeout 值
    或者设置 sqlalchemy 的 pool_recycle 值
    geew
        2
    geew  
    OP
       2013-08-29 10:13:48 +08:00
    @caoyue pool_recycle=30 新浪sae的超时是30秒, 但是这样了还有问题
    wzxjohn
        3
    wzxjohn  
       2013-08-29 10:15:21 +08:00
    SAE的mysql相当不稳定,这个问题出了很久了。淡定。
    hit9
        4
    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
        5
    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
        6
    geew  
    OP
       2013-08-29 11:50:41 +08:00
    @luckyduck sqlalchemy有类似的机制吗 pool_recycle选项貌似不起作用
    luckyduck
        7
    luckyduck  
       2013-08-29 11:58:53 +08:00
    @geew 你可以试试把pool_recycle设置成5,再运行一段时间看会不会还报这个错。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5200 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:02 · PVG 17:02 · LAX 02:02 · JFK 05:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.