在Debian系统上实现PostgreSQL的读写分离,通常需要以下几个步骤:
安装和配置PostgreSQL:
确保你已经安装了PostgreSQL,并且有一个主节点(master)和一个或多个从节点(slave)。你可以使用apt
包管理器来安装PostgreSQL。
sudo apt update
sudo apt install postgresql postgresql-contrib
配置主节点:
编辑主节点的postgresql.conf
文件,确保以下参数设置正确:
listen_addresses = '*' # 允许所有IP连接
wal_level = replica # 设置为replica以支持流复制
max_wal_senders = 10 # 允许的最大WAL发送者数量
wal_keep_segments = 64 # 保留的WAL段数量
编辑pg_hba.conf
文件,添加从节点的连接权限:
host replication replicator <slave_ip>/32 md5
重启PostgreSQL服务以应用更改:
sudo systemctl restart postgresql
配置从节点:
编辑从节点的postgresql.conf
文件,确保以下参数设置正确:
listen_addresses = '*' # 允许所有IP连接
hot_standby = on # 启用热备模式
编辑recovery.conf
文件(在较新的PostgreSQL版本中可能是postgresql.auto.conf
),添加主节点的连接信息:
standby_mode = 'on'
primary_conninfo = 'host=<master_ip> dbname=<dbname> user=<replicator> password=<password>'
restore_command = 'cp /var/lib/postgresql/<version>/main/wal_archive/%f %p'
trigger_file = '/tmp/postgresql.trigger.5432'
确保从节点的数据目录中有足够的空间来存储WAL归档。
重启PostgreSQL服务以应用更改:
sudo systemctl restart postgresql
使用pgpool-II或PgBouncer:
为了更方便地管理读写分离,你可以使用pgpool-II
或PgBouncer
这样的连接池器。
pgpool-II: 安装pgpool-II:
sudo apt install pgpool2
配置pgpool.conf
文件,设置主从节点的信息:
backend_hostname0 = 'master_ip'
backend_port0 = 5432
backend_weight0 = 1
backend_hostname1 = 'slave_ip'
backend_port1 = 5432
backend_weight1 = 1
配置pg_hba.conf
文件,添加pgpool-II的连接权限:
host all all 127.0.0.1/32 md5
host all all ::1/128 md5
重启pgpool-II服务:
sudo systemctl restart pgpool2
PgBouncer: 安装PgBouncer:
sudo apt install pgbouncer
配置pgbouncer.ini
文件,设置主从节点的信息:
[databases]
mydb = host=master_ip dbname=mydb user=replicator password=password
[pgbouncer]
listen_port = 6432
listen_addr = 127.0.0.1
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 100
default_pool_size = 20
创建用户列表文件/etc/pgbouncer/userlist.txt
:
[pgbouncer]
replicator = md5<password>
重启PgBouncer服务:
sudo systemctl restart pgbouncer
通过以上步骤,你可以在Debian系统上实现PostgreSQL的读写分离。主节点处理写操作,而从节点处理读操作,从而提高数据库的性能和可用性。