PostgreSQL 16: 参数 reserved_connections

John Doe 六月 26, 2025

你有没有为数据库服务端的连接数不够而烦恼过?

在山坡奔跑的大象

特性提交日志

添加新的 GUC 参数 reserved_connections。

这一参数提供了为非超级用户预留连接槽位的方式。通过这个新的 GUC 参数预留的槽位,仅对拥有预定义角色 pg_use_reserved_connections 的用户可用。当 reserved_connections 的预留槽位耗尽时,superuser_reserved_connections 将作为最后预留的槽位继续发挥作用。

讨论:http://postgr.es/m/20230119194601.GA4105788@nathanxps13

示例

在之前的 PostgreSQL 版本中,可以通过设置 superuser_reserved_connections 参数,为超级用户保留连接。PostgreSQL 新版本引入了新参数和新角色,您将拥有更多选择。新角色名为 pg_use_reserved_connections:

postgres=# \du *reserved*
                     List of roles
          Role name          |  Attributes  | Member of
-----------------------------+--------------+-----------
 pg_use_reserved_connections | Cannot login | {}

新的参数称为 reserved_connections,默认情况下处于禁用状态:

postgres=# \dconfig *reserved*
    List of configuration parameters
           Parameter            | Value
--------------------------------+-------
 reserved_connections           | 0
 superuser_reserved_connections | 3
(2 rows)

将该角色授予用户,设置参数并重新启动实例将为您提供新功能:

CREATE USER u WITH LOGIN PASSWORD 'u';
CREATE USER x WITH LOGIN PASSWORD 'x';
GRANT pg_use_reserved_connections to u;
ALTER SYSTEM SET max_connections = 5;
ALTER SYSTEM SET reserved_connections = 1;
$ pg_ctl restart
waiting for server to shut down.... done
server stopped
waiting for server to start.... done
server started
postgres=# \dconfig *connections*
    List of configuration parameters
           Parameter            | Value
--------------------------------+-------
 log_connections                | off
 log_disconnections             | off
 max_connections                | 5
 reserved_connections           | 1
 superuser_reserved_connections | 3
(5 rows)

使用此配置,用户“x”将只能创建一个连接。任何其他连接请求都将失败:

$ psql -U x postgres &
[2] 17310

$ psql -U x postgres &
[3] 17312
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed:
FATAL:  remaining connection slots are reserved for roles with privileges of pg_use_reserved_connections

[3]   Exit 2                  psql -U x postgres

用户“u”将能够创建一个来自预留连接的连接。任何其他连接请求也将失败,因为剩余的连接槽已为超级用户保留:

$ psql -U u postgres &
[3] 17318

$ psql -U u postgres &
[4] 17320
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed:
FATAL:  remaining connection slots are reserved for superusers

[4]   Exit 2                  psql -U u postgres

很好,除了为超级用户预留连接槽之外,如果您对系统进行相应配置,也可以为普通用户预留连接槽。

非常不错的特性。感谢社区的所有相关人员。

参考

提交日志:https://git.postgresql.org/pg/commitdiff/6e2775e4d4e47775f0d933e4a93c148024a3bc63