后端长时间无数据库请求后,第一次恢复请求会报错,错误信息是这样的:
sqlalchemy.exc:OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly This probably
means the server terminated abnormally before or while processing the request.[SQL: SELECT visitor."ID" AS "visitor_ID",
visitor.username AS visitor_username, visitor.visits AS visitor_visits FROM visitor](Background on this error at: http://sqlalche.me/e/e3q8)
这篇文章说的比较清楚了——数据库对长时间idle的连接有超时关闭的处理机制,sqlalchemy的连接池也有超时释放的处理机制。
当连接池的超时时间长于数据库的连接超时时间时,可能出现数据库已经关闭一个连接,而客户端还以为这个连接仍然有效的情况。
查了一下postgresql的超时时间默认值:
archive_timeout
控制服务器周期性地切换到一个新的 WAL 段文件,通俗的讲,就是定时归档。
authentication_timeout
完成服务器认证的最长时间,如果在这个时间内没有完成认证,服务器将关闭连接。
checkpoint_timeout
自动 WAL 检查点之间的最长时间,增大这个参数会使数据库崩溃后恢复的时间加长。
deadlock_timeout
进行死锁检测之前在一个锁上等待的总时间
idle_in_transaction_session_timeout
空闲事务超时。终止任何已经闲置超过这个参数所指定的时间(以毫秒计)的打开事务的会话。 这使得该会话所持有的任何锁被释放,并且其所持有的连接槽可以被重用, 它也允许只对这个事务可见的元组被清理。
lock_timeout
锁等待超时。语句在试图获取表、索引、行或其他数据库对象上的锁时等到超过指定的毫秒数,该语句将被中止。不推荐在postgresql.conf中设置。
statement_timeout
控制语句执行时长,单位是ms。超过设定值,该语句将被中止。
不推荐在postgresql.conf中设置,如非要设置,应该设置一个较大值。
wal_receiver_timeout
中止处于非活动状态超过指定毫秒数的复制链接。这对于正在接收的后备服务器检测主服务器崩溃或网络断开有用。设置为0会禁用超时机制。这个参数只能在postgresql.conf文件中或在服务器命令行上设置。默认值是 60 秒。
wal_sender_timeout
中断那些停止活动超过指定毫秒数的复制连接。这对发送服务器检测一个后备机崩溃或网络中断有用。设置为0将禁用该超时机制。这个参数只能在postgresql.conf文件中或在服务器命令行上设置。默认值是 60 秒。
————————————————
版权声明:本文为CSDN博主「数据库人生」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ctypyb2002/article/details/79548630
暂时还没有找到connect_timeout 的默认时间是从哪儿来的。
数据库端没有这个选项。
在libpq的源码里面也没有找到这个变量有默认设置 。
libpq-int.h
fe-connect.c
typedef struct _PQconninfoOption
{
char *keyword; /* The keyword of the option */
char *envvar; /* Fallback environment variable name */
char *compiled; /* Fallback compiled in default value */
char *val; /* Option's current value, or NULL */
char *label; /* Label for field in connect dialog */
char *dispchar; /* Indicates how to display this field in a
* connect dialog. Values are: "" Display
* entered value as is "*" Password field -
* hide value "D" Debug option - don't show
* by default */
int dispsize; /* Field size in characters for dialog */
} PQconninfoOption;
{"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
"Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
psycopg2的源码里面也没有找到…
暂时先不找了。
3.0版本的sqlclchemy_engine设置方法如下。
It seems that some connections were kept by SQLAlchemy for too long. I lowered the POOL_RECYCLE_TIME to 10 minutes and updated the settings format to avoid deprecation that will be introduced in version 3.0 of Flask-SQLAlchemy.
DB_POOL_SIZE = int(os.environ.get('DB_POOL_SIZE', '10'))
DB_POOL_RECYCLE = int(os.environ.get('DB_POOL_RECYCLE', '60'))
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_size': DB_POOL_SIZE,
'pool_recycle': DB_POOL_RECYCLE,
}
Original: https://blog.csdn.net/qq_39597358/article/details/115444743
Author: Goodwillie
Title: flask 使用sqlalchemy连接postgreSQL,长期无活动,出现异常断开的解决方案
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/747982/
转载文章受原作者版权保护。转载请注明原作者出处!