Fastapi 项目第二天首次访问时数据库连接报错问题Can‘t connect to MySQL server

问题描述

Fastapi 项目使用 sqlalchemy 连接的mysql 数据库,每次第二天首次访问数据库相关操作,都会报错:sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'x.x.x.x' ([Errno 111] Connection refused)")

问题分析

从出现问题的规律看,每次都是长时间不操作数据库,再操作时就会报错,但是第二次操作又正常访问了,说明跟数据库的连接超时有关。

数据库中通过以下命令查看超时时间

复制代码
show VARIABLES like 'wait_timeout%'

wait_timeout 默认是28800秒,即mysql链接在无操作8个小时后被自动关闭,如果服务器长时间处于空闲状态,再次访问mysql数据库的时候,数据库会拒绝访问。

SQLALCHEMY 配置数据库时

复制代码
engine = create_engine(SQLALCHEMY_DATABASE_URL)

create_engine 有个pool_recycle 参数

此设置会使池在经过给定的秒数后回收连接。它默认为-1,或者没有超时。例如,设置为3600意味着连接将在一小时后回收。请注意,如果在八个小时的连接中没有检测到任何活动,

MySQL尤其会自动断开连接(尽管这可以通过MySQLDB连接本身和服务器配置进行配置)

复制代码
    :param pool_recycle=-1: this setting causes the pool to recycle
        connections after the given number of seconds has passed. It
        defaults to -1, or no timeout. For example, setting to 3600
        means connections will be recycled after one hour. Note that
        MySQL in particular will disconnect automatically if no
        activity is detected on a connection for eight hours (although
        this is configurable with the MySQLDB connection itself and the
        server configuration as well).

        .. seealso::

            :ref:`pool_setting_recycle`

解决问题

使用python的sqlalchemy连接数据库,不指定连接池的配置pool_recycle时,默认配置的连接回收pool_recycle=-1,就是永远不会回收。

mysql配置当中默认连接超过8小时,当超过8个小时没有新的数据库请求的时候,数据库连接就会断开,

如果我们连接池的配置是用不关闭或者关闭时间超过8小时,这个时候连接池没有回收并且还认为连接池与数据库之间的连接还存在,就会继续连接,但是数据库连接断开了,就会报错数据库连接失败!

解决办法:

  1. 修改mysql配置文件里wait_timeout参数,让这个时间大于连接池的回收时间(修改配置文件需要重启数据库,不推荐!)

  2. sqlalchemy将连接池连接回收时间设置小于8小时:

    engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_recycle=3600) # 设置1小时

相关推荐
zizle_lin2 小时前
优雅使用Gunicorn进程管理FastAPI
服务器·fastapi·gunicorn
掘金-我是哪吒2 天前
分布式微服务系统架构第131集:fastapi-python
分布式·python·微服务·系统架构·fastapi
Anesthesia丶4 天前
Vue3 + naive-ui + fastapi使用心得
vue.js·ui·fastapi
weixin_307779134 天前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
掘金-我是哪吒4 天前
分布式微服务系统架构第130集:Python工程化FastAPI,运维Nginx-keepalived+Nginx实现高可用集群
运维·分布式·微服务·系统架构·fastapi
LingRannn4 天前
JWT的介绍与在Fastapi框架中的应用
fastapi
Python私教5 天前
使用FastAPI和React以及MongoDB构建全栈Web应用05 FastAPI快速入门
前端·react.js·fastapi
Python私教5 天前
全栈开发实战:FastAPI + React + MongoDB 构建现代Web应用
前端·react.js·fastapi
weixin_307779136 天前
使用FastAPI和Apache Flink构建跨环境数据管道
redis·python·云计算·fastapi·aws
真智AI9 天前
构建安全的机器学习推理API:基于FastAPI的用户认证与管理实战
安全·机器学习·fastapi