如何在重负载下强制停止长 postgres 查询?

How to forcefully stop long postgres query under heavy load?

我正在 Ubuntu 上使用 Postgres 开发 Rails 应用程序。对我来说不幸的是,这个遗留应用程序在数据库中使用了一些重量级的存储过程。更重要的是,数据库很大(5GB),我的电脑也不是特别快。时不时地,如果我将一些错误的参数从我的代码传递到数据库,我的计算机会变得非常慢,以至于我无法到达控制台并终止 postgres 进程。我想,这是由于一些非常昂贵的数据库查询。我唯一的解决办法是硬重置我的笔记本电脑。所以我的问题是 - 有没有办法强行终止长时间查询?或者,有没有办法限制 CPU 和允许数据库使用的 RAM,这样我还有一些资源可以去手动重启 postgres?

您可以使用 statement_timeout 配置选项设置语句的最长时间:

Abort any statement that takes more than the specified number of milliseconds, starting from the time the command arrives at the server from the client. If log_min_error_statement is set to ERROR or lower, the statement that timed out will also be logged. A value of zero (the default) turns this off.

您可以通过多种方式设置此选项,例如在 postgresql.conf 中针对每个人,在每个会话中使用 SET command, or even per database or per role. More information on setting options is in the documentation