PostgreSQL13.1

1. Introduction to PostgreSQL

1.1 What is PostgreSQL?

PostgreSQL database is currently the most powerful open source database, supporting rich data types (such as JSON and JSONB types, array types) and custom types. Moreover, it provides a rich interface, which can easily expand its functions, such as implementing its own index type under the GiST framework, etc. It also supports writing custom functions and triggers in C language, and also supports the use of popular languages Write custom functions, for example, PL/Perl provides the function of writing custom functions in Perl language, and of course PL/Python, PL/Tcl, and so on. It was first developed by Michael Stonebraker, a computer science professor at the University of Ontario, Canada, and his colleagues in 1986, initially as an application for the Ingres database management system. In 1995, PostgreSQL officially became an independent project.

PostgreSQL is excellent in many aspects, such as scalability, concurrent access, integrity, security, etc., and is increasingly favored by more and more developers and enterprises. It is not only a reliable data storage and query engine, but also provides a rich function library, data types and APIs that support multiple programming languages. More importantly, it is free to use and is not affected by commercial interests.

Following are some of the features and benefits of PostgreSQL:

  • Support ACID transactions to ensure data integrity.
  • The query optimizer can quickly optimize and execute complex queries.
  • Provides a series of complex data types, such as arrays, JSON, XML, etc.
  • Support extensions, such as PL/Python, PL/Perl and other language extensions.
  • Detailed documentation and an active community are provided, making it easy to learn and use.

1.2 What are the advantages and disadvantages of PostgreSQL database?

1.2.1 The main advantages of PostgreSQL are as follows:

(1) The maintainer is the PostgreSQL Global Development Group, first released in June 1989.

(2) The operating system supports WINDOWS, Linux, UNIX, MAC OS X, and BSD.

(3) From the perspective of basic functions, it supports ACID, relational integrity, database transactions, and Unicode multi-language.

(4) In terms of tables and views, PostgreSQL supports temporary tables, and materialized views can be simulated using stored procedures and triggers in PL/pgSQL, PL/Perl, PL/Python or other procedural languages.

(5) In terms of indexing, it fully supports R-/R+tree indexing, hash indexing, reverse indexing, partial indexing, Expression indexing, GiST, GIN (used to speed up full-text retrieval), and supports bitmap indexing from version 8.3.

(6) On other objects, it supports data fields, stored procedures, triggers, functions, external calls, and cursors. 7) In terms of data table partitioning, it supports 4 types of partitions, namely range, hash, mix, and list.

(7) From the perspective of transaction support, compared with MySQL, the transaction support has undergone a more thorough test.

(8) In terms of MyISAM table processing, MySQL uses table locking for non-transactional MyISAM tables, and a long-running query is likely to hinder the update of the table, while PostgreSQL does not have such a problem.

(9) From the perspective of stored procedures, PostgreSQL supports stored procedures. Because the existence of stored procedures also avoids the transmission of a large number of original SQL statements on the network, such advantages are obvious.

(10) In terms of extension of user-defined functions, PostgreSQL can be more conveniently extended using UDF (user-defined functions).

1.2.2 The application disadvantages of PostgreSQL are as follows:

(1) The latest version and the historical version are not stored separately, resulting in more scans required to clean up the old version, which is relatively expensive, but the general database has a peak period. If VACUUM is properly arranged, this is not a big problem. And VACUUM has been further enhanced in PostgreSQL9.0.

(2) In PostgreSQL, because the index has no version information at all, Coverage index scan cannot be implemented, that is, the query only scans the index, and cannot directly return the required attributes from the index, and needs to access the table, while Oracle and Innodb can.

1.3 Feature comparison between different major versions of PostgreSQL

  • pg9 uses inherited partitioning, pg10 implements declarative partitioning, pg11 improves functions, and pg12 improves performance
Version new features
pg9 1. Inherited partitioning
2. Manually add triggers or rules
pg10 1. Declarative partitioning
2. Partition indexes are created manually and cannot be created based on the partition parent table
pg11 1. Add hash partition
2. Create index based on partition table
3. Support update partition
4. Will create a default default partition
5. Partition supports the creation of primary key, foreign key, index, trigger
pg12 1. New hash partition
2. alter table attach partitions will not block the query
pg13 1. Support before trigger (it is not allowed to change the target partition of inserted data)
2. Support logical replication

1.4 Comparison between OpenGauss and PostgreSQL

1. The most available mode most_available_sync
pg stream replication has always had a pain point. In the one-master-slave synchronization mode, if the standby database goes down, the main database will hang, and the synchronization mode will not be automatically degraded. It needs to rely on third-party tools for judgment and monitoring , or use one master and multiple backup quorums to prevent the impact of standby database exceptions on the main database.
The maximum available mode is supported in openGauss. After enabling this parameter, it will be in synchronous mode when the master-slave connection is normal. If the standby machine is disconnected, it will immediately switch to asynchronous mode. If the standby machine starts up again, it will automatically connect and switch to synchronous mode.
This downgrade switching time is very fast, the switching process will not even hang, and there is no timeout window parameter to set, which is a disadvantage.

2. The xid cannot be exhausted.
OpenGauss changes the transactionid from int32 to int64. The 64-bit xid can never be exhausted. Although the xid is changed to 64-bit, the expired xid still needs to be cleaned by freeze, but never worry about xid rollback Risk of downtime.

3. Automatic creation of physical streaming replication environment
After the master-slave streaming replication environment is built in openGauss, a physical replication slot whose slot_name is the peer nodename will be automatically created by default, in order to prevent the xlog required by the standby library from being deleted or cleaned up by the main library.

4. Incremental checkpoints
openGauss supports incremental checkpoints, which are enabled by the enable_incremental_checkpoint parameter. When the checkpoint in Pg is executed, all the dirty pages in the buffer will be flushed to the disk, and the dirty page flushing action needs to be completed within the checkpoint_timeout*checkpoint_completion_target time. Cleaning dirty pages is a very costly action for the database. The incremental checkpoints in Gaussian will clean the dirty pages in small batches and stages in a rolling manner, while updating the lsn information and recycling unnecessary xlog logs.

5. Double write double write
We know that the data block of the operating system is 4k, and the database is generally 8k/16k/32k, which may cause page breaks. A database data block may be down during the process of flashing to the operating system, resulting in block damage The database could not be started.
mysql solves this problem through double write, oracle doesn’t care about this problem, and if something happens, it can be restored through rman or dg standby database. pg solves this problem through full_page_write, which is to write the entire page when the data page changes for the first time. It is recorded in the xlog log, so that if there is a problem, there will be a complete data page plus xlog log for recovery, but the problem brought about by this is that the log volume of xlog is greatly increased, and it also has a certain impact on performance.
openGauss implements double-write similar to mysql. When writing data blocks, dirty pages are also written to a shared double-write space. If a problem occurs, a complete data page will be found from the double-write space for recovery. The double-write feature parameter enable_double_write needs to be used together with incremental checkpoints.

6. Enhanced client password authentication
The default password encryption algorithm of pg is md5, and openGauss is enhanced to sha256. This function needs to be compatible with the modification of the client.

7. xlog pre-allocation
The xlog log in pg will allocate the next log after it is full. The problem brought about by this is that there will be a wait when the operating system writes a 16M xlog log, and it may be stuck at that time. It is also the reason why the performance of pg jitters when doing concurrent insert tests.
OpenGauss implements xlog pre-allocation, and allocates one or more xlogs below when the xlog is not full, and the performance of the pressure test is relatively stable.

8. Stream replication thread connection authentication
In openGauss, when the primary and backup replication threads want to connect to the peer server, ssl authentication is required by default. pg is not required, which enhances security. Authentication can be turned off by setting remote_read_mode to non_authentication (if not turned off, The relevant ca certificate key needs to be configured, otherwise the database will fail to start in -M primary/standby mode).

9. The dbe_perf performance monitoring schema
openGauss will have a dbe_perf performance monitoring view by default under each library, which is similar to the performance_schema of mysql, and there are hundreds of performance views in it. Although most of these views are available in pg, they can be created separately The schema is convenient for viewing and management.

10. In the stream replication environment, the maximum number of archived xlogs in the main library is limited
. The hard limit of the maximum xlog value is controlled by the max_size_for_xlog_prune parameter. It does not matter whether the deletion of the xlog will affect the standby machine, as long as it exceeds this value, it will be deleted. It can prevent the main library directory from bursting due to long-term disconnection of the master and backup

11. Public schema security authority enhancement
openGauss enhances the security of the default public schema under each database. By default, ordinary users do not have permission to create objects under public, and authorization is required. I dare not say whether this is an improvement, because since it is called public, it is for everyone to use.

12. Eliminate the recovery.conf file.
Use replconninfo to configure the master-standby connection information. Application_name and other related configurations are merged into postgresql.conf to simplify the process and facilitate the switchover between the master and the backup. The pg12 stream replication also discards the recovery.conf file.

13. Data page-based replication
openGauss supports redo-based replication, data page-based replication, and two mixed replications, which are controlled by the enable_data_replicate and enable_mix_replication parameters

14. Support column storage table, column storage buffer
openGauss supports column storage table, control the size of column storage buffer through cstore_buffers, column storage table supports compression. In addition, the current version of Gauss optimizes the concurrent insertion performance of the column storage table, and solves the problem that a row of data occupies one CU during insertion, causing the space to expand rapidly. By enabling the enable_delta_store parameter to control the insertion of the column storage table, use the temporary table to merge with the main table, which not only ensures performance, but also solves the problem of expansion

15. Memory table
Support llvm-based memory query engine, support high throughput, low latency access.

16. NUMA architecture optimization
By binding numa cores, it reduces the delay of cross-core memory access, improves CPU utilization, improves the synchronization performance between multiple threads, inserts xlog logs in batches, and processes hot data in a decentralized manner.

17. User resource management
Support cpu memory limit in multi-tenant environment, configure resource pool, and call operating system cgroup to realize.

18.wdr report
supports performance reports similar to oracle awr.

19. The memory pool memory pool
manages the database memory usage at a higher level, limiting the maximum physical memory available to a database node.

20. Query memory limit query_mem
can limit the memory used by a certain query.

21. Asynchronous direct io
enables disk pre-allocation and io prefetching to improve write performance.

22. Performance enhancement of column store delta merge
Turn on the enable_delta_store parameter to control the insertion of the column store table and use the temporary table to merge with the main table to improve performance and solve swelling.

23. Parallel playback
Supports parallel playback of logs on the standby machine to improve replication performance.

24. Session timeout
The Session_timeout parameter controls the session timeout period to prevent unexpected database downtime caused by long-term unreleased threads.

25. Master-slave and one-master-multiple-standby
not only support one-master-multiple-slave mode, but also support master-slave-slave mode. The master-slave machine directly physically replicates, and the slave machine has no data by default. When the main database goes down, the standby machine and the slave machine form a new Copy the relationship, and start copying data from the machine, which saves space and ensures high availability.

26. Thread pool
The process model is changed to a thread model. The thread pool supports tens of thousands of concurrency. The decoupling between session and thread is realized through the thread pool to improve the utilization rate of threads. High concurrency will not cause frequent switching of threads.

27. The commit log is changed from 256k to 16M
in order to match the 64-bit xid.

1.4.1 Face up to the shortcomings

1. The pg_stat_replication view is lost
. The basic view of viewing the replication status in pg has been lost. Although the status can also be replicated using the gs_ctl query command, pg_stat_replication can also view the master-slave lag information, which cannot be queried in Gaussian.

2. Compilation is too complicated and depends too much
Compilation requires a lot of dependencies, and the version is fixed, making cross-platform compilation very difficult and poor platform versatility. You may find that compiling Huawei's third-party compiling tools is more troublesome than compiling databases.

3. Does not support parallelism
Currently Gaussian does not support parallelism, and hopes to introduce the parallelism function supported by pg9.6 in the future.

4. Without postgresql.auto.conf,
you cannot use alter system set to configure related parameters

5. Does not support pitr
Currently does not support point-in-time recovery, it is said that version 830 will support it.

6. Does not support plug-ins
This is a great disadvantage. The good scalability of pg is that it supports plug-ins, which attracts many developers to develop plug-ins based on pg, but plug-ins are no longer supported in openGauss.

7. The community has just started, and the participation rate is not high.
The openGauss community has just started, and the current activity is not high. I hope it will get better in the future, and I hope that the excellent features of Gauss can also be absorbed by pg.

8. Peripheral tools
High availability tools and data synchronization tools are not available.

9. There is a gap between performance and native pg.
Using concurrency tools to pressure test the database code speed finds that there is a gap with native pg. At the same time, parallelism is not supported at present, so analysis scenarios are also insufficient.

10. copydir restriction
In openGauss, the database data import directory is limited to pg_copydir under the data directory. This is a very inhumane design. Imagine that the production environment needs derivatives, and it needs to be copied to the data directory first, which may easily cause the data directory to be full.

1.5 PostgreSQL Chinese Community

insert image description here

PostgreSQL Chinese community:
http://www.postgres.cn/index.php/v2/home

2. Install

1. Create a user

[root@localhost ~]# useradd postgres

2. Download the installation package

Installation package download address:

https://ftp.postgresql.org/pub/source/v13.1/postgresql-13.1.tar.gz

3. Unzip

[root@localhost src]# tar xf postgresql-13.1.tar.gz

4. Compile and install

[root@localhost src]# cd postgresql-13.1/

--prefix=xxx 指定安装位置,默认会将程序安装到/usr/local/pgsql下
[root@localhost postgresql-13.1]# ./configure --prefix=/opt/pgsql            
[root@localhost postgresql-13.1]# make && make install

5. Create the database data directory

[root@localhost postgresql-13.1]# mkdir -p /opt/pgsql/data
[root@localhost postgresql-13.1]# chown postgres.postgres /opt/pgsql/data/

6. Initialize the database

[root@localhost postgresql-13.1]# su postgres
[postgres@localhost postgresql-13.1]$ /opt/pgsql/bin/initdb -D /opt/pgsql/data/

7. Start the database

[postgres@localhost postgresql-13.1]$ /opt/pgsql/bin/pg_ctl -D /opt/pgsql/data/ -l logfile start
查询postgresql端口,默认端口号为5432
[postgres@localhost postgresql-13.1]$ ss -antl|grep 5432
LISTEN     0      128        *:5432         *:*                  
LISTEN     0      128       [::]:5432         [::]:*            

查询postgresql运行状态
[postgres@localhost postgresql-13.1]$ /opt/pgsql/bin/pg_ctl -D /opt/pgsql/data/ -l logfile status
pg_ctl: server is running (PID: 12307)
/opt/pgsql/bin/postgres "-D" "/opt/pgsql/data"

连接数据库
[postgres@localhost postgresql-13.1]$ /opt/pgsql/bin/psql 
psql (13.1)
Type "help" for help.

postgres=#

8. Edit environment variables

//为了方便执行,编辑postgres用户的PATH环境变量
[postgres@localhost postgresql-13.1]$ vim ~/.bashrc
export PATH=/opt/pgsql/bin:$PATH
[postgres@localhost postgresql-13.1]$ source ~/.bashrc

3. Set up remote connection

创建用户,设置密码
postgres=# create database cxdata;
CREATE DATABASE
postgres=# alter user postgres with password 'cxdata@123';
ALTER ROLE
修改文件1
注:文件中每行前面的序号为行号,编辑的时候直接输入行号gg,就可以到达指定行。
[postgres@localhost postgresql-13.1]$ vim /opt/pgsql/data/postgresql.conf
59 listen_addresses = '*'
修改文件2
其中0.0.0.0/0表示运行任意ip地址访问,设置md5开启密码验证
[postgres@localhost postgresql-13.1]$ vim /opt/pgsql/data/pg_hba.conf
88 local   all             all                                     md5
90 host   all             all             0.0.0.0/0                 md5
重启数据库
[postgres@localhost postgresql-13.1]$ /opt/pgsql/bin/pg_ctl -D /opt/pgsql/data/ -l logfile stop
[postgres@localhost postgresql-13.1]$ /opt/pgsql/bin/pg_ctl -D /opt/pgsql/data/ -l logfile start

Test remote connection
Host: 192.168.5.57
Database: cxdata
Username: postgres
Password: cxdata@123

insert image description here
If the above screen appears, it means success.

4. Common commands

  1. pg_ctl is a command-line tool to initialize, start, stop, and control PostgreSQL server
-D 数据目录
pg_ctl -D /opt/pgsql/data/ start    //启动
pg_ctl -D /opt/pgsql/data/ stop    //关闭
pg_ctl -D /opt/pgsql/data/ restart  //重启
pg_ctl -D /opt/pgsql/data/ status  //查看服务状态

2. Connect to the database

-U 指定用户  -d 指定数据库 -h 要链接的主机 -W 提示输入密码

psql -U postgres  (psql -U username -d databse_name -h host -W)

3. Switch database

\c dbname

4. List

\dt
5.查看表结构
\d tblname
6.查看索引
\di

7. Create a database

create database dbname;

8. Delete the database

drop database dbname;

9. Rename a table

alter table [表名A] rename to [表名B]

10. Delete a table

drop table

For more common commands, please check:
https://www.coonote.com/note/postgresql-cmd.html

5. PostgreSQL performance optimization

Please check this article:
https://blog.csdn.net/LG_15011399296/article/details/123705384

6. Data backup and recovery

6.1 Full database backup

//全备
[root@localhost pgsql]# pg_dumpall -h 127.0.0.1 -U postgres > /opt/all_dbbak.sql

//导入数据库
[root@localhost pgsql]# psql -h 127.0.0.1 -U postgres < /opt/all_dbbak.sql

6.2 Single database backup

//单备
[root@localhost ~]# pg_dump -h 127.0.0.1 -U postgres school > /opt/school.sql

//导入数据库
[root@localhost ~]# psql -U postgres school </opt/school.sql

6.3 Table backup

//创建表
school=# create table student (id int, name char(32), age int);

//备份表
[root@localhost ~]# pg_dump -h 127.0.0.1 -U postgres school -t student >/opt/student.sql
school=# drop table student;

//导入表
[root@localhost ~]# psql -U postgres -d school </opt/student.sql

7. Master-slave replication

Master-slave replication principle
insert image description here

  1. The active and standby databases are started, the standby database starts the wal_receiver process, and the wal process sends a connection request to the main database;
  2. The main library starts the wal_sender process after receiving the connection request, and establishes a tcp connection with the wal_receiver process;
  3. The standby wal_receiver process sends the latest wal lsn to the main library;
  4. The main library performs lsn comparison, periodically sends heartbeat information to the standby database to confirm the availability of the standby database, and sends the undelivered wal log files, and calls the SyncRepWaitForLSN() function to obtain the latch, and waits for the standby database to respond; The release timing of the latch is related to the selection of the master-standby synchronization mode;
  5. The standby library calls the operating system write() function to write the wal file into the cache, then calls the operating system fsync() function to refresh the WAL to the disk, and then plays back the WAL file; at the same time, the standby library returns ack confirmation information to the main library, and the ack information contains Contains write_lsn, flush_lsn, and replay_lsn, which are used to inform the main database of the current WAL log application location and status in the standby database. The relevant location information can be viewed through the pg_stat_replication view;
  6. If the hot_standby_feedback parameter is enabled, the standby library will periodically send xmin information to the main library to ensure that the main library will not vacuum the tuple information required by the standby library

7.1 Master node configuration

Environment description:

system version IP Role database version
CentOS7.6 192.168.5.57 host postgresql-13.1
CentOS7.6 192.168.5.58 from postgresql-13.1

prerequisites:

  • The pgsql single node installation has been completed
  1. Create a dedicated user for user replication
[root@localhost ~]# psql -Upostgres -d postgres
postgres=# create user repl login replication encrypted password 'repl';
  1. Modify the main configuration file postgresql.conf
[postgres@localhost root]$ vim /opt/pgsql/data/postgresql.conf
59 listen_addresses = '*'
290 max_wal_senders = 32       //同步最大的进程数量
  1. Modify the configuration file pg_hba.conf
[postgres@localhost root]$ vim /opt/pgsql/data/pg_hba.conf
96 host    replication     repl            192.168.5.0/24          md5
  1. Restart the master node

7.2 Slave node configuration

prerequisites:

  • The pgsql single node installation has been completed
  1. Stop the service and delete the data in the data directory
[postgres@localhost postgresql-13.1]$ /opt/pgsql/bin/pg_ctl -D /opt/pgsql/data/ -l logfile stop
waiting for server to shut down.... done
server stopped
[postgres@localhost postgresql-13.1]$ rm -rf /opt/pgsql/data/*
  1. Pull master node data remotely
[postgres@localhost bin]$ ./pg_basebackup -h 192.168.5.57 -D /opt/pgsql/data/ -U repl -P -v -R -X stream -C -S pgstandby1
Password: 
pg_basebackup: initiating base backup, waiting for checkpoint to complete
pg_basebackup: checkpoint completed
pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1
pg_basebackup: starting background WAL receiver
pg_basebackup: created replication slot "pgstandby1"
32179/32179 kB (100%), 1/1 tablespace                                         
pg_basebackup: write-ahead log end point: 0/2000138
pg_basebackup: waiting for background process to finish streaming ...
pg_basebackup: syncing data to disk ...
pg_basebackup: renaming backup_manifest.tmp to backup_manifest
pg_basebackup: base backup completed

复制后从节点的配置文件会和主节点的一样,并且一并复制的还有数据库文件,里面的数据也一样,意味着主节点有什么用户数据从节点也有。

-h –指定作为主服务器的主机。
-D –指定数据目录。
-U –指定连接用户。
-P –启用进度报告。
-v –启用详细模式。
-R–启用恢复配置的创建:创建一个standby.signal文件,并将连接设置附加到数据目录下的postgresql.auto.conf。
-X–用于在备份中包括所需的预写日志文件(WAL文件)。流的值表示在创建备份时流式传输WAL。
-C –在开始备份之前,允许创建由-S选项命名的复制插槽。
-S –指定复制插槽名称。
[postgres@localhost data]$ cat postgresql.auto.conf 
# Do not edit this file manually!
# It will be overwritten by the ALTER SYSTEM command.
primary_conninfo = 'user=repl password=repl channel_binding=disable host=192.168.5.57 port=5432 sslmode=disable sslcompression=0 ssl_min_protocol_version=TLSv1.2 gssencmode=disable krbsrvname=postgres target_session_attrs=any'
primary_slot_name = 'pgstandby1'
[postgres@localhost data]$
  1. Restart the database

7.4 Verify master-slave

  1. View master node replication slots
postgres=# SELECT * FROM pg_replication_slots;
-[ RECORD 1 ]-------+-----------
slot_name           | pgstandby1
plugin              | 
slot_type           | physical
datoid              | 
database            | 
temporary           | f
active              | t
active_pid          | 2338
xmin                | 
catalog_xmin        | 
restart_lsn         | 0/3000060
confirmed_flush_lsn | 
wal_status          | reserved
safe_wal_size       |
  1. master node information
postgres=# SELECT * FROM pg_stat_replication;
-[ RECORD 1 ]----+------------------------------
pid              | 2338
usesysid         | 24604
usename          | repl
application_name | walreceiver
client_addr      | 192.168.5.58
client_hostname  | 
client_port      | 53320
backend_start    | 2023-06-13 11:13:37.124903+08
backend_xmin     | 
state            | streaming
sent_lsn         | 0/3000060
write_lsn        | 0/3000060
flush_lsn        | 0/3000060
replay_lsn       | 0/3000060
write_lag        | 
flush_lag        | 
replay_lag       | 
sync_priority    | 0
sync_state       | async
reply_time       | 2023-06-13 11:14:36.53047+08
  1. Slave node information
postgres=# SELECT * FROM pg_stat_wal_receiver;
  pid  |  status   | receive_start_lsn | receive_start_tli | written_lsn | flushed_lsn | received_tli |      last_msg_send_time       |     last_msg_receipt_time     | latest_end_lsn |        latest_end_tim
e        | slot_name  | sender_host  | sender_port |                                                                                                                                  conninfo                                                                                                                           
-------+-----------+-------------------+-------------------+-------------+-------------+--------------+-------------------------------+-------------------------------+----------------+----------------------
---------+------------+--------------+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
 10997 | streaming | 0/3000000         |                 1 | 0/3001CD8   | 0/3001CD8   |            1 | 2023-06-13 11:53:40.527471+08 | 2023-06-13 11:53:39.837223+08 | 0/3001CD8      | 2023-06-13 11:22:07.5
94397+08 | pgstandby1 | 192.168.5.57 |        5432 | user=repl password=******** channel_binding=disable dbname=replication host=192.168.5.57 port=5432 fallback_application_name=walreceiver sslmode=disable 
sslcompression=0 ssl_min_protocol_version=TLSv1.2 gssencmode=disable krbsrvname=postgres target_session_attrs=any
(1 row)
  1. Create a library in the main library, go to the slave library to view
主库操作
postgres=# create database pyd;
CREATE DATABASE
从库操作
postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 pyd       | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 school    | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | postgres=CTc/postgres+
           |          |          |             |             | =c/postgres
(5 rows)

7.4 Master-slave switching

  1. Stop the main library
[postgres@localhost data]$ pg_ctl -D /opt/pgsql/data/ -l logfile stop -m fast
  1. Start the standby database to provide external services
[postgres@localhost pgsql]$ ./bin/pg_ctl -D /opt/pgsql/data/ promote
[postgres@localhost pgsql]$ ./bin/pg_controldata -D /opt/pgsql/data/   
 #查看状态为in production对外提供服务,另外standby.signal文件自动删除
  1. Change the old primary to the new standby database and resynchronize
重建standby.signal文件
[postgres@localhost ~]$ cd /opt/pgsql/data/
[postgres@localhost data]$ touch standby.signal
[postgres@localhost data]$ vim postgresql.auto.conf
primary_conninfo = 'user=repl password=repl channel_binding=disable host=192.168.5.58 port=5432 sslmode=disable sslcompression=0 ssl_min_protocol_version=TLSv1.2 gssencmode=disable krbsrvname=postgres target_session_attrs=any'

primary_slot_name = 'pgstandby1'


新主库若没有配置复制槽,需要配置下
SELECT * FROM pg_create_physical_replication_slot(‘pgstandby1’);
SELECT slot_name, slot_type, active FROM pg_replication_slots;
 
启动备库
[postgres@localhost ~]$ pg_ctl -D /opt/pgsql/data/ start 
pg_controldata #查看状态为in archive recovery

Guess you like

Origin blog.csdn.net/qq_49530779/article/details/131400159