ProxySQL PostgreSQL 配置
在 ProxySQL(3.0+ 版本)中配置 PostgreSQL,需要通过专用管理端口 6132 操作 pgsql_* 系列配置表,并执行 LOAD 和 SAVE 使配置生效。以下为标准的读写分离与代理配置步骤:
ProxySQL 为 PostgreSQL 提供了独立的管理端口(默认 6132)和业务代理端口(默认 6133)。使用 psql 客户端连接管理界面:
psql -h 127.0.0.1 -p 6132 -U admin
# 默认密码为 admin
在 pgsql_servers 表中添加主库(写组,例如 hostgroup_id = 10)和从库(读组,例如 hostgroup_id = 20):
-- 添加主库 (Hostgroup 10)
INSERT INTO pgsql_servers (hostgroup_id, hostname, port) VALUES (10, '10.0.0.11', 5432);
-- 添加只读从库 (Hostgroup 20)
INSERT INTO pgsql_servers (hostgroup_id, hostname, port) VALUES (20, '10.0.0.12', 5432);
-- 加载并持久化
LOAD PGSQL SERVERS TO RUNTIME;
SAVE PGSQL SERVERS TO DISK;
在后端 PostgreSQL 数据库中创建一个低权限的监控账号,随后在 ProxySQL 全局变量中绑定该账号:
-- 在后端 PostgreSQL 主库执行
CREATE USER proxysql_monitor WITH PASSWORD 'MonitorPassword123';
请谨慎使用此类代码。
sql
-- 在 ProxySQL 管理界面 (6132端口) 执行
SET pgsql-monitor_username='proxysql_monitor';
SET pgsql-monitor_password='MonitorPassword123';
SET pgsql-monitor_connect_interval=2000;
SET pgsql-monitor_ping_interval=2000;
LOAD PGSQL VARIABLES TO RUNTIME;
SAVE PGSQL VARIABLES TO DISK;
可通过查询 SELECT * FROM monitor.pgsql_server_ping_log; 验证节点连通性。
将业务连接 PostgreSQL 的账号和密码写入 pgsql_users,并指定默认路由的主机组(通常设为写组 10):
INSERT INTO pgsql_users (username, password, default_hostgroup)
VALUES ('app_user', 'AppPassword123', 10);
LOAD PGSQL USERS TO RUNTIME;
SAVE PGSQL USERS TO DISK;
通过 pgsql_query_rules 表利用正则表达式匹配 SQL 语句,实现读写分离(非事务内的 SELECT 路由至读组 20,其余默认走 default_hostgroup 即写组 10):
-- 排除 SELECT ... FOR UPDATE,将普通 SELECT 转发至读组 20
INSERT INTO pgsql_query_rules (rule_id, active, match_digest, destination_hostgroup, apply)
VALUES (1, 1, '^SELECT.*FOR UPDATE', 10, 1);
INSERT INTO pgsql_query_rules (rule_id, active, match_digest, destination_hostgroup, apply)
VALUES (2, 1, '^SELECT', 20, 1);
LOAD PGSQL QUERY RULES TO RUNTIME;
SAVE PGSQL QUERY RULES TO DISK;
完成配置后,应用程序即可通过 6133 端口连接 ProxySQL 代理:
psql -h 127.0.0.1 -p 6133 -U app_user -d postgres
更多高阶参数(如连接池复用、SCRAM-SHA-256 认证及主从自动故障转移配合)可参考 ProxySQL 官方 PostgreSQL 配置文档。
特定需求:
- 高可用架构(如配合 Patroni 或 Orchestrator 实现自动主从切换)
- 认证方式(如 SCRAM-SHA-256 密码加密配置)
- 性能调优(如连接池大小与预编译语句缓存)