PGBouncer 不会重用连接,而是不断创建新的数据库连接,直到耗尽为止

问题描述 投票:0回答:2

我有几个客户端(FreeRadius 服务器)连接到一个中央 Pgbouncer。 当我使用这些 FreeRadius 服务器之一时,我可以看到 Pgbouncer 创建了多个数据库连接。

select *
from pg_stat_activity
where datname = 'master_db';

当我再次使用同一个 freeradius 服务器时,pgbouncer 不会重新使用现有的打开连接,而是不断创建新连接。一旦我达到超过 30 个连接,整个数据库就会停止。

PGbouncer.ini

server_idle_timeout = 10
max_client_conn = 500
default_pool_size = 30

postgresql.conf:(Postgres 13)

max_connections = 150

根据我的研究,Pgbouncer 应该为客户端分配单个数据库连接(从 default_pool_size 开始),然后创建客户端需要的尽可能多的内部连接(最多 max_client_conn)。

但我在这里观察到的情况恰恰相反。请问我还缺少什么吗?

更新: Laurenz 建议的解决方案有效,但在幕后使用 asyncpg 时会抛出此错误:

NOTE: pgbouncer with pool_mode set to "transaction" or "statement" does not support prepared statements properly. You have two options: * if you are using pgbouncer for connection pooling to a single server, switch to the connection pool functionality provided by asyncpg, it is a much better option for this purpose; * if you have no option of avoiding the use of pgbouncer, then you can set statement_cache_size to 0 when creating the asyncpg connection object.

postgresql freeradius pgbouncer
2个回答
0
投票

您将需要使用

session
选项
POOL_MODE
,以便它能够维护由 asyncpg 由于异步性质而打开的连接会话

您应该在您的

如果使用

pgbouncer.ini
文件

[pgbouncer]
pool_mode = session
...
...
...

或者如果使用环境变量

POOL_MODE=session

extra source:
https://magicstack.github.io/asyncpg/current/faq.html#why-am-i-getting-prepared-statement-errors

如果您收到间歇性准备好的陈述 “asyncpg_stmt_xx”不存在或准备好的语句 “asyncpg_stmt_xx”已经存在错误,你很可能没有 直接连接到 PostgreSQL 服务器,但通过 pgbouncer。 pgbouncer,当处于“交易”或“语句”池模式时,不会 不支持准备好的陈述。您有多种选择:

如果您仅使用 pgbouncer 来减少新连接的成本 (与使用 pgbouncer 进行大型连接池相反) 为了更好的可扩展性),切换到 asyncpg提供的连接池功能,是一个非常多的功能 为此目的更好的选择;

通过传递禁用自动使用准备好的语句 statements_cache_size=0 到 asyncpg.connect() 和 asyncpg.create_pool() (并且,显然,避免使用 Connection.prepare());

将 pgbouncer 的 pool_mode 切换为 session。


0
投票

从 PgBouncer 1.21.0 开始,它现在支持事务池模式下的协议级别名为准备好的语句,这几乎肯定会解决此错误。您可以通过在 PgBouncer 的配置文件中将

max_prepared_statements
设置为非零值来打开此支持。有关详细信息,请查看文档:https://www.pgbouncer.org/config.html#max_prepared_statements

© www.soinside.com 2019 - 2024. All rights reserved.