推荐学习书目
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 · Feb 26, 2015 · 3364 views
    This topic created in 4119 days ago, the information mentioned may be changed or developed.
    MySQL server has gone away

    一般我是直接修改my.cnf

    wait_timeout=31536000
    interactive_timeout=31536000


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

    MySQLdb貌似没有重连机制。


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

    except
    lianghui
        3
    lianghui  
       Feb 27, 2015
    你这配置太逗,服务器基本设置为10秒idle 给你一个客户端的重置参考下

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

    from sqlalchemy import create_engine
    e = create_engine("mysql://scott:tiger@localhost/test", pool_recycle=3600)
    lianghui
        6
    lianghui  
       Feb 28, 2015   ❤️ 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
       Feb 28, 2015
    @lianghui 谢谢, 以前看过dbutils的一些,不过我确实需要解决多种数据库适配,最后还是用sqla全部来做了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1082 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 101ms · UTC 23:22 · PVG 07:22 · LAX 16:22 · JFK 19:22
    ♥ Do have faith in what you're doing.