Ste*_*han 39 postgresql connection timeout
有些客户端连接到我们的postgresql数据库,但保持连接打开.是否有可能告诉Postgresql在一定量的不活动后关闭这些连接?
TL; DR
如果您使用的是Postgresql版本> =
9.2
那么请使用我提出的解决方案如果您不想编写任何代码,
那么使用arqnid的解决方案
Ste*_*han 44
对于那些感兴趣的人,这是我提出的解决方案,灵感来自Craig Ringer的评论:
(...)使用cron作业查看连接上次活动时的时间(请参阅pg_stat_activity)并使用pg_terminate_backend杀死旧的.(...)
选择的解决方案如下:
- 的连接被认为是不活动的,如果它的状态或者是
idle
,idle in transaction
,idle in transaction (aborted)
或disabled
.- 连接被认为是旧的,如果其状态时超过5分钟保持不变.
rank()
功能)这是线程运行的SQL查询:
WITH inactive_connections AS (
SELECT
pid,
rank() over (partition by client_addr order by backend_start ASC) as rank
FROM
pg_stat_activity
WHERE
-- Exclude the thread owned connection (ie no auto-kill)
pid <> pg_backend_pid( )
AND
-- Exclude known applications connections
application_name !~ '(?:psql)|(?:pgAdmin.+)'
AND
-- Include connections to the same database the thread is connected to
datname = current_database()
AND
-- Include connections using the same thread username connection
usename = current_user
AND
-- Include inactive connections only
state in ('idle', 'idle in transaction', 'idle in transaction (aborted)', 'disabled')
AND
-- Include old connections (found with the state_change field)
current_timestamp - state_change > interval '5 minutes'
)
SELECT
pg_terminate_backend(pid)
FROM
inactive_connections
WHERE
rank > 1 -- Leave one connection for each application connected to the database
Run Code Online (Sandbox Code Playgroud)
fre*_*sko 14
如果您使用的是PostgreSQL> = 9.6,那么还有一个更简单的解决方案。假设您想每5分钟删除一次所有空闲连接,只需运行以下命令:
alter system set idle_in_transaction_session_timeout='5min';
Run Code Online (Sandbox Code Playgroud)
如果您无权以超级用户身份访问(例如Azure云上的示例),请尝试:
SET SESSION idle_in_transaction_session_timeout = '5min';
Run Code Online (Sandbox Code Playgroud)
但是,后者仅适用于当前会话,这很可能不是您想要的。
要禁用此功能,
alter system set idle_in_transaction_session_timeout=0;
Run Code Online (Sandbox Code Playgroud)
要么
SET SESSION idle_in_transaction_session_timeout = 0;
Run Code Online (Sandbox Code Playgroud)
(顺便说一下,0是默认值)。
如果使用alter system
,则必须重新加载配置才能开始更改,并且更改是持久的,例如,如果您要重新启动服务器,则不必重新运行查询。
要检查功能状态:
show idle_in_transaction_session_timeout;
Run Code Online (Sandbox Code Playgroud)
如果您将 AWS 与 PostgreSQL >= 9.6 一起使用,则必须执行以下操作:
转到 RDS > 参数组 > 创建参数组 选择您使用的 PSQL 版本,将其命名为“customParameters”或其他名称,并添加描述“处理空闲连接”。
幸运的是,它将创建默认 AWS 组的副本,因此您只需调整您认为不适合您的用例的内容。
现在单击新创建的参数组并搜索“空闲”。
'idle_in_transaction_session_timeout' 的默认值设置为 24 小时(86400000 毫秒)。将此数字除以 24 以获得小时数 (3600000),然后您必须再次将 3600000 除以 4、6 或 12,具体取决于您希望超时分别为 15、10 或 5 分钟(或等效地乘以分钟数 x 60000,所以值 300 000 5 分钟)。
最后但并非最不重要的是,更改组:
转到 RDS,选择您的数据库并单击“修改”。
现在在“数据库选项”下,您将找到“数据库参数组”,将其更改为新创建的组。
然后,您可以决定是否要立即应用修改(注意停机时间)。
归档时间: |
|
查看次数: |
55865 次 |
最近记录: |