V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Koril
V2EX  ›  PostgreSQL

关于 PostgreSQL 中的 max_connections 和 pg_stat_activity 的疑惑

  •  
  •   Koril · 4 天前 · 576 次点击

    问题描述

    各位大佬,有个问题请教下 我在本地( Windows11 )安装了一个 PostgreSQL ,一切都是默认值安装

    我通过以下语句查到 max connections 的值是 100

    show max_connections; -- 返回 100
    

    我猜测这个应该就是 PG 默认的最大连接数,然后我用 Python 写了一个脚本,循环获取 connection:

    import psycopg2
    import time
    
    def get_db_conn():
        conn = psycopg2.connect(host='localhost',port=5432,database='study_demo',user='postgres',password='123456')
        return conn
    
    def main():
        conn_list = list()
        for i in range(100):
            print(f'获取第 {i} 个连接')
            try:
                conn_list.append(get_db_conn())
            except Exception:
                print(f'获取第 {i} 个连接失败')
        print(f'成功获取 {len(conn_list)} 个连接')
        time.sleep(60)
        
    if __name__ == '__main__':
        main()
    

    然后代码显示获取到了 95 个连接,然后我通过以下 SQL 获取连接数

    select count(*) from pg_stat_activity; -- 返回 105
    

    我预测的值应该是:

    1. Python 获取到 90 个连接(因为执行 Python 脚本前,就有 10 个连接了,这几个连接可能是开了 Navicat 和 pgAdmin4 的缘故)
    2. pg stat activity 最后应该正好是 100 或者 99 (留一个连接给超级用户?)

    但是结果完全不一样,105 明显超过了,这多出来的 5 个是如何得到的?

    3 条回复    2024-09-13 21:03:44 +08:00
    ampedee
        1
    ampedee  
       4 天前 via iPhone   ❤️ 1
    pg stat activity 返回结果是连接进程状态的超集,除了会话进程,还有其他辅助进程,你可以看下输出字段加个筛选条件
    XueXianqi
        2
    XueXianqi  
       4 天前
    应该还有一个地方可以设置类似于 MAX_OVERFLOW 的参数,允许溢出的连接数
    Koril
        3
    Koril  
    OP
       4 天前
    @ampedee 我找了下,应该指的是 backend_type 字段吧,SQL 加个 where backend_type = 'client backend' 数量就对象了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5518 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 06:05 · PVG 14:05 · LAX 23:05 · JFK 02:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.