geew
V2EX  ›  问与答

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

  •  
  •   geew · Aug 29, 2013 · 4849 views
    This topic created in 4661 days ago, the information mentioned may be changed or developed.
    在新浪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 replies    1970-01-01 08:00:00 +08:00
    caoyue
        1
    caoyue  
       Aug 29, 2013
    可能是长时间没有操作请求导致连接被关闭了
    设置 MySQL 的 interactove_timeout 值
    或者设置 sqlalchemy 的 pool_recycle 值
    geew
        2
    geew  
    OP
       Aug 29, 2013
    @caoyue pool_recycle=30 新浪sae的超时是30秒, 但是这样了还有问题
    wzxjohn
        3
    wzxjohn  
       Aug 29, 2013
    SAE的mysql相当不稳定,这个问题出了很久了。淡定。
    hit9
        4
    hit9  
       Aug 29, 2013
    ```
    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  
       Aug 29, 2013
    这个问题在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
       Aug 29, 2013
    @luckyduck sqlalchemy有类似的机制吗 pool_recycle选项貌似不起作用
    luckyduck
        7
    luckyduck  
       Aug 29, 2013
    @geew 你可以试试把pool_recycle设置成5,再运行一段时间看会不会还报这个错。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5871 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 93c8b4a0 · 40ms · UTC 06:31 · PVG 14:31 · LAX 23:31 · JFK 02:31
    ♥ Do have faith in what you're doing.