修改 Postgres 参数

本页目录

如果你需要更改 Postgres 参数 (又称之为 GUC,Grand Unified Configuration) 以实现永久效果,请按照以下步骤操作。

参考文档:设置参数

1) 确认是否需要重启

快速检查是否需要重启的两种方法:

PSQL
nik=# select name, context
from pg_settings
where name in ('max_wal_size', 'shared_buffers');
      name      |  context
----------------+------------
 max_wal_size   | sighup
 shared_buffers | postmaster
(2 rows)

2) 进行更改

在 Postgres 配置文件中应用更改 (postgresql.conf 或其依赖项,如果使用了 include 命令的话)。除非必要,建议避免使用 ALTER SYSTEM,以免将来产生混淆 (它会写入 postgresql.auto.conf,且可能很容易被忽视;参见相关讨论)。

3) 应用更改

如果需要重启,则重启 Postgres。如果忘记重启,稍后可以在 pg_settings 中查看 pending_restart 来检测未应用的更改。

如果不需要重启,在超级用户下执行:

SQL
select pg_reload_conf();

或者使用以下方法之一:

当应用了无需重启的更改时,Postgres 日志中会显示类似以下内容:

Shell
LOG: received SIGHUP, reloading configuration files
LOG: parameter "max_wal_size" changed to "2GB"

4) 验证更改

使用 SHOW 或 current_setting(...) 确认更改已生效,例如:

PSQL
nik=# show max_wal_size;
 max_wal_size
--------------
 2GB
(1 row)

或者

PSQL
nik=# select current_setting('max_wal_size');
 current_setting
-----------------
 2GB
(1 row)

额外信息:数据库级、用户级和表级设置

如果 pg_settings 中的 context 为 user 或 superuser,那么可以在数据库或用户级别调整设置,例如:

SQL
alter database verbosedb set log_statement = 'all';
alter user hero set statement_timeout = 0;

这些结果可以在 pg_db_role_setting 中查看:

PSQL
nik=# select * from pg_db_role_setting;
 setdatabase | setrole |       setconfig
-------------+---------+-----------------------
       24580 |       0 | {log_statement=all}
           0 |   24581 | {statement_timeout=0}
(2 rows)

当使用 CREATE TABLE 或 ALTER TABLE 时,某些设置还可以在表级别进行调整,参照 CREATE TABLE / Storage Parameters。请注意命名差异:autovacuum_enabled 用于启用或禁用特定表的 autovacuum 守护进程,而全局设置名称为 autovacuum。

我见

在 15 中,还支持了 \dconfig 命令,也很方便。

The \dconfig command can display the parameter settings of the instance. If no option is specified, a list of parameters that have changed from the default values is displayed. If a parameter name is specified, the specific parameter setting value can be checked. Wildcards can be used for parameter names.

PSQL
postgres=# \dconfig *mem*
     List of configuration parameters
            Parameter             | Value 
----------------------------------+-------
 autovacuum_work_mem              | -1
 dynamic_shared_memory_type       | posix
 enable_memoize                   | on
 hash_mem_multiplier              | 2
 logical_decoding_work_mem        | 64MB
 maintenance_work_mem             | 64MB
 min_dynamic_shared_memory        | 0
 multixact_member_buffers         | 256kB
 shared_memory_size               | 145MB
 shared_memory_size_in_huge_pages | 73
 shared_memory_type               | mmap
 work_mem                         | 4MB
(12 rows)

讨论与补充

在 GitHub 查看讨论

支持作者

感谢支持 PostgreSQL Howto 的长期维护。

微信赞赏码

读者交流群

二维码若已过期,可通过公众号 PostgreSQL 学徒或邮件联系。

PostgreSQL 学徒读者交流群二维码