# 修改储存路径

```shell
systemctl edit postgresql-13.service
```

```service
[Service]
Environment=PGDATA=/home/postgresql/13/data/
```



# 添加postgres账户环境变量

```shell
vi .bash_profile
```

```
PGDATA=/home/postgresql/13/data/
```

```shell
vi .pgsql_profile
```

```sh
PATH=/usr/pgsql-13/bin:$PATH
export PATH
```

# 配置读写分离

1. 登录postgres账户,修改主服务器配置文件：postgresql.conf

    ```conf
    listen_addresses= '*'
    wal_level = replica
    archive_mode = on
    archive_command = 'cp %p /data/postgresql/archive/%f'
    max_wal_senders= 10
    wal_keep_size = 1000		# in megabytes; 0 disables
    max_slot_wal_keep_size = 10	# in megabytes; -1 disables
    wal_sender_timeout = 120s	# in milliseconds; 0 disables
    hot_standby = on
    ```

2. 新建用户用于主从复制

   ```sql
   create user replica REPLICATION  LOGIN ENCRYPTED  PASSWORD 'asdf*123';
   ```

3. 将主从IP添加到hba配置文件：pg_hba.conf
   ```
   host    replication     replica         192.168.0.0/24 md5
   host    all     all         0.0.0.0/0           md5
   ```
4. 在从服务器新建文件夹：

   ```shell
   mkdir -p /home/postgresql/13/data/
   ```
5. 在从服务器执行命令在线热备份

   ```shell
   pg_basebackup -h 192.168.0.10 -U replica -F p -X s -v -P -R -D $PGDATA
   ```
6. 在从服务器执行命令启动服务器
   ```shell
   pg_ctl start
   ```
7. 主服务器测试
    ```shell
    psql
    ```
    ```sql
    select client_addr,sync_state from pg_stat_replication;
    ```
    查看是否有从服务器连接
# 备份恢复

```shell
# 备份
pg_dumpall -h 127.0.0.1 -U postgres > /var/lib/pgsql/bakup1221.bakup
# 恢复服务器从备份服务器下载备份文件
scp postgres@192.168.0.3:"/var/lib/pgsql/bakup1221.bakup" /var/lib/pgsql/
# 恢复，使用postgres账号
psql -f bakup1221.bakup postgres
```



























