V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
jamiesun
V2EX  ›  Python

关于 MySQLdb 重连的问题

  •  
  •   jamiesun ·
    jamiesun · 2015-02-26 22:37:27 +08:00 · 2839 次点击
    这是一个创建于 3360 天前的主题,其中的信息可能已经有所发展或是发生改变。
    MySQL server has gone away

    一般我是直接修改my.cnf

    wait_timeout=31536000
    interactive_timeout=31536000


    不过最近阿里云RDS连续3次主备切换,还是断。

    MySQLdb貌似没有重连机制。


    你们是如何解决的,比如这种数据库当机后恢复的情况
    7 条回复    2015-02-28 09:42:53 +08:00
    VYSE
        1
    VYSE  
       2015-02-26 23:59:00 +08:00 via Android
    conn.ping(True)
    cursor=....
    lincanbin
        2
    lincanbin  
       2015-02-27 00:06:36 +08:00
    from warnings import filterwarnings
    filterwarnings('error', category = MySQLdb.Warning)
    令Warning变为error,然后就可以开始捕获了
    try

    except
    lianghui
        3
    lianghui  
       2015-02-27 08:58:25 +08:00
    你这配置太逗,服务器基本设置为10秒idle 给你一个客户端的重置参考下

    https://github.com/thomashuang/dbpy/blob/master/db/mysql/connection.py
    jamiesun
        4
    jamiesun  
    OP
       2015-02-28 00:01:36 +08:00
    @lianghui 你这个是短连接的搞法,我用的是连接池。连接池没有实现ping,自动重连。
    jamiesun
        5
    jamiesun  
    OP
       2015-02-28 00:30:04 +08:00
    看来还是没有仔细读sqla的文档,加个参数就ok了,再也不用暴力解决问题了

    from sqlalchemy import create_engine
    e = create_engine("mysql://scott:tiger@localhost/test", pool_recycle=3600)
    lianghui
        6
    lianghui  
       2015-02-28 09:30:01 +08:00   ❤️ 1
    @jamiesun 对于idle的处理在pool和连接类处理问题idle问题不大,基本都是要每次使用check, 不过你已经用sqla,不过还是推荐你看看连接池的实现,你也可以去看看sqla的pool实现,不过他的pool为了适配多种数据库engine有很多特殊的处理,比如线程安全,然后什么queuepool,异步pool之类的
    https://github.com/thomashuang/dbpy/blob/master/db/_db.py
    https://github.com/thomashuang/dbpy/blob/master/db/pool.py
    jamiesun
        7
    jamiesun  
    OP
       2015-02-28 09:42:53 +08:00
    @lianghui 谢谢, 以前看过dbutils的一些,不过我确实需要解决多种数据库适配,最后还是用sqla全部来做了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1355 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:51 · PVG 01:51 · LAX 10:51 · JFK 13:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.