설치 및 pgpool-II의 사용

 

간략한 소개

pgpool-II는 다음과 같은 기능을 제공하는 중간과 PostgreSQL PostgreSQL 데이터베이스 클라이언트 서버 사이에 위치하고 있습니다 :

  • 연결 풀링

        들어오는 접속들이 (예를 들어 사용자 이름, 데이터베이스, 프로토콜 버전)을 재사용하는 경우 : pgpool-II는 PostgreSQL 서버를 유지하고, 동일한 매개 변수를 사용하여 커넥터를 연결하고있다. 이것은 오버 헤드의 연결을 감소시키고, 시스템의 전체적인 처리량을 증가시킨다.

  • 복사

       pgpool-II는 여러 서버의 PostgreSQL를 관리 할 수 ​​있습니다. 하나 개의 노드가 실패 할 경우 PostgreSQL을 두 개 이상의 노드가, 서비스가 중단없이 계속 작동 할 수 있습니다 그래서, 복사 기능 가능한 실시간 백업의 설립을 활성화합니다.

  • 로드 균형 조정

       데이터베이스가 복제되는 경우, 동일한 결과를 반환합니다 하나의 서버에 SELECT 쿼리를 실행합니다. 각 서버의 PostgreSQL에 부하를 줄이기 위해 복제 기능을 사용하여 pgpool-II. 시스템의 전체 처리량을 향상에 사용 가능한 모든 서버에 배포하여 쿼리를 선택합니다. 이상적인 상황에서, 및 읽기 성능 PostgreSQL를 서버의 수에 직접적으로 비례해야한다. 로드는 동시에 많은 수의 사용자에 매우 기능적 많은 장면이 가장 잘 작동에 읽기 전용 쿼리를 수행합니다.

  • 제한 연결 제한을 초과

       PostgreSQL는이 수에 도달 할 때, 새로운 접속이 거부되며, 현재 연결의 최대 수를 제한한다. 이 연결의 최대 수 자원의 소비를 증가 증가하고 시스템의 전반적인 성능에 부정적인 영향을 미칠 것입니다. pgpoo-II는 또한 연결의 최대 수를 제한 지원하지만 그 방법은 즉시 오류를 반환하기보다는, 대기열에 연결하는 것입니다.

  • 병렬 쿼리

       병렬 쿼리를 사용하는 경우, 데이터는 쿼리 전체 실행 시간을 줄이기 위해, 다수의 서버상에서 동시에 수행 할 수 있도록하는 것이, 여러 서버에 분할 될 수있다. 쿼리 병렬 쿼리 대규모 데이터는 매우 효과적인 경우.

       pgpool-II 표리 PostgreSQL의 프로그램 사이에 사용되는 프로토콜, 및 전후 간의 메시지를 전달한다. 따라서 pgpool-II 간주 (프론트 엔드) 데이터베이스 애플리케이션은 실제 PostgreSQL 데이터베이스이며, 백엔드 서버 프로세스는 pgpool-II가 하나의 클라이언트로 간주된다. pgpool-II는 서버와 클라이언트에 투명하기 때문에, 기존 데이터베이스 응용 프로그램은 실질적으로 pgpool-II의 수정없이 사용할 수있다.

차트

다음 실험.

실험을 시작하기 전에 모든 서버 방화벽 및 SELinux를 닫습니다.

데이터베이스 구성

구성 마스터 터미널

1) 구성 pg_hba.conf 파일

local   all             all                                     trust
host    all             all             127.0.0.1/32            trust
host    all             all             192.168.0.0/16          trust
host    all             all             ::1/128                 trust
host	replication		all				192.168.100.0/24		trust

2) 구성 파일을 postgresql.conf

log_destination = 'stderr'		
logging_collector = on		
log_directory = 'pg_log'		
log_filename = 'postgresql-%Y-%m-%d.log'	
log_duration = on
log_error_verbosity = default		
log_line_prefix = '%m'			
log_statement = 'all'		
wal_level = hot_standby
archive_mode = on
archive_command = 'cp %p /usr/local/pgsql/archive/%f'
max_wal_senders = 3
hot_standby = on

기본 백업을 수행합니다

1) 데이터베이스 서비스를 다시 시작

2) 열기 상시 대기

psql -c "select pg_start_backup('backup');"

3) 기본 백업

[root@master pgsql]# tar zcf data.tgz data							

4) 닫기 상시 대기

[postgres@master bin]$ psql -c "select pg_stop_backup()"

5) 대기로 데이터를 복사

[root@master pgsql]# scp data.tgz 192.168.100.140:/usr/local/pgsql

2. 구성 대기 종료

1) 데이터베이스를 중지

[postgres@slave bin]$ ./pg_ctl -D ../data stop

2), 디렉토리 데이터를 삭제 data.tgz를 통해 마스터 터미널에서 복사본을 추출

[root@slave pgsql]# rm -rf data							
[root@slave pgsql]# tar -zxvf data.tgz 							

3) 설정 recovery.conf

standby_mode = on
recovery_target_timeline = 'latest'
primary_conninfo = 'host=192.168.100.140 port=5432 user=postgres password=####'
trigger_file = '/usr/local/pgsql/trigger_file'

4) 시작 대기

[postgres@slave bin]$ ./pg_ctl -D ../data start

설치 구성 pgpool-II

모든 데이터베이스 서비스는 구성 pgpool-II, 설치해야합니다.

설치 준비 :

[root@master ~]#chmod +s /bin/ping
[root@master ~]#chmod +s /sbin/ifup
[root@master ~]#chmod +s /sbin/ip
[root@master ~]#chmod +s /sbin/ifconfig
[root@master ~]#chmod +s /sbin/arping

설치 1

1) 루트 사용자 및 구성 디렉토리 권한에 대한 데이터베이스 디렉토리를 생성

[root@master ~]# mkdir -p /usr/local/pgpool
[root@master ~]# chown -R postgres:postgres /usr/local/pgpool

2)) 루트 사용자 환경 변수 (/root/.bashrc 파일을 사용

export PATH=$PATH:$HOME/bin:/usr/local/pgpool/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/pgpool/lib

3) 설치

포스트 그레스 사용자 설치에 :

[postgres@master ~]$ cd pgpool-II-3.2.9/
[postgres@master pgpool-II-3.2.9]$ ./configure --prefix=/usr/local/pgpool
[postgres@master pgpool-II-3.2.9]$ make
[postgres@master pgpool-II-3.2.9]$ make install

4) pgpool-II 온라인 복구 및 부팅 관리자에 대한 pgpool_recovery, pgpool_remote_start, pgpool_switch_xlog을 제공, 별도로 컴파일 된 데이터베이스에서 만든 설치해야

[postgres@master pgpool-II-3.2.9]$ cd sql/pgpool-recovery/
[postgres@master pgpool-recovery]$ make && make install
[postgres@master pgpool-II-3.2.9]$ cd sql/pgpool-regclass/
[postgres@master pgpool-regclass]$ make && make install

SQL 데이터베이스에서 수행 단계를 수행하면 노드 마스터 서버에서만 수행 할 수 있습니다, 대기 서버는 스트림을 복사하여 동기화됩니다 :

[postgres@master pgpool-regclass]$ cd /usr/local/pgsql/share/contrib/
[postgres@master contrib]$ psql -f pgpool-recovery.sql -U postgres template1
[postgres@master contrib]$ psql -f pgpool-recovery.sql -U postgres postgres
[postgres@master contrib]$ psql -f pgpool-regclass.sql -U postgres template1
[postgres@master contrib]$ psql -f pgpool-regclass.sql -U postgres postgres

따라서 pgpool-II 설치를 완료합니다.

2. 구성

1) 시작 구성 파일 pgpool.conf

[postgres@master etc]$ cp pgpool.conf.sample pgpool.conf

파일의 내용을 수정 Pgpool.conf :

# - pgpool Connection Settings -
listen_addresses = '*'
port = 9999
socket_dir = '/tmp'
pcp_port = 9898
pcp_socket_dir = '/tmp'


# - Backend Connection Settings -配置后台连接的数据库
backend_hostname0 = '192.168.100.140'
backend_port0 = 5432
backend_weight0 = 1
backend_data_directory0 = '/usr/local/pgsql/data'
backend_flag0 = 'ALLOW_TO_FAILOVER'
backend_hostname1 = '192.168.100.142'
backend_port1 = 5432
backend_weight1 = 1
backend_data_directory1 = '/usr/local/pgsql/data'
backend_flag1 = 'ALLOW_TO_FAILOVER'

# - Authentication -对连接认证进行配置
enable_pool_hba = on
pool_passwd = 'pool_passwd'
authentication_timeout = 60

# FILE LOCATIONS
pid_file_name = '/usr/local/pgpool/pgpool.pid'

# CONNECTION POOLING 连接池配置
connection_cache = on

# REPLICATION MODE 不起用复制模式
replication_mode = off

# LOAD BALANCING MODE 启用负载均衡模式
load_balance_mode = on

# MASTER/SLAVE MODE 启用主从模式
master_slave_mode = on
master_slave_sub_mode = 'stream' #以流复制模式配置主从

# - Streaming -
sr_check_period = 10 #检查流复制状态周期
sr_check_user = 'postgres' #数据库用户
sr_check_password = '####'  #数据库用户密码
delay_threshold = 10000000 #默认值

# - Special commands -
follow_master_command = '' #只有两节点,所以不需要配置该命令

# PARALLEL MODE 不起用并行模式
parallel_mode = off

# HEALTH CHECK 健康状况检查相关参数
health_check_period = 20
health_check_timeout = 10
health_check_user = 'postgres'
health_check_password = '####' #数据库用户密码
health_check_max_retries = 0
health_check_retry_delay = 1

# FAILOVER AND FAILBACK 执行failover脚本
failover_command = '/usr/local/pgpool/etc/failover.sh %d %H /usr/local/hgdb/trigger_file'
failback_command = ''
fail_over_on_backend_error = on

# ONLINE RECOVERY online recovery相关参数
recovery_user = 'postgres' #数据库用户
recovery_password = '####' #数据库用户密码
recovery_1st_stage_command = 'basebackup.sh' #放在脚本$PGDATA目录
recovery_2nd_stage_command = ''
recovery_timeout = 90
client_idle_limit_in_recovery = 0

# WATCHDOG watchdog配置
use_watchdog = on
trusted_servers = '192.168.100.254 #网关,用来判断网络可用性,可以为空
delegate_IP = '192.168.100.160' #虚拟地址,对外提供服务
wd_hostname = '192.168.100.140' #master服务器中,此处填192.168.100.140;slave服务器中,此处填192.168.100.142
wd_port = 9000
wd_interval = 10
ping_path = '/bin'
ifconfig_path = '/sbin'
if_up_cmd = 'ifconfig eth0:0 inet $_IP_$ netmask 255.255.255.0'
if_down_cmd = 'ifconfig eth0:0 down'
arping_path = '/usr/sbin' 
arping_cmd = 'arping -U $_IP_$ -w 1'
wd_life_point = 3
wd_lifecheck_query = 'SELECT 1'

# Other pgpool Connection Settings
other_pgpool_hostname0 = '192.168.100.142'#需要监控的对方IP,即master服务器中,此处填192.168.100.142;slave服务器中,此处填192.168.100.140
other_pgpool_port0 = 9999
other_wd_port0 = 9000

2) 설정 파일을 수정하고 pcp.conf를 시작합니다 :

MD5 키를 만들기 :

postgres@master ~]$ cd /usr/local/pgpool/bin
[postgres@master bin]$ ./pg_md5 -p postgres

pcp.conf 사용 :

[postgres@master etc]$ cp pcp.conf.sample pcp.conf

파일의 내용을 수정 Pcp.conf :

# USERID:MD5PASSWD
postgres:e8a48653851e28c69d0506508fb27fc5 -->该串字符,即为刚刚生成的md5密钥

3) 활성화 pool_hba.conf 프로필

[postgres@master etc]$ cp pool_hba.conf.sample pool_hba.conf

다음과 같이 파일의 내용에 추가 :

host    all         all         192.168.100.0/16      trust

설정 호스트 신뢰

1.root 사용자의 신뢰

[root@master ~]# ssh-keygen -t rsa -P ''
[root@master ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@master ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]

사용자의 신뢰를 2.postgres

[postgres@master ~]$ ssh-keygen -t rsa -P ''
[postgres@master ~]$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[postgres@master ~]$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]

3.root 사용자 신뢰와 사용자 포스트 그레스

[root@master ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@master ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[postgres@master ~]$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[postgres@master ~]$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]

pgpool-II 관리

1. 시작 및 종료 다운 (루트 사용자)

시작 명령

[root@master ~]# pgpool

직접 출력하지 디버그 정보를 시작할 수 있습니다 :

[root@master ~]# pgpool -n -d > /tmp/pgpool.log 2>&1 &

pgpool 백그라운드 디버그 모드를 설정, 디버그 로그 출력은 /tmp/pgpool.log합니다.

명령을 닫습니다 :

pgpool stop [-m {s[mart]|f[ast]|i[mmediate]}]

정지는 세 가지 모드가 있습니다 : "스마트", "빨리", "즉시"

smart-- 닫은 후 분리에 고객을 기다리는

fast--, 분리에 고객을 기다리는 즉시 종료되지

그것은 빠르고 모드가됩니다 immediate--

2. 노드 중 하나는 pgpool (포스트 그레스 사용자)에 연결

[postgres@master etc]$ psql -p 9999

노드 상태보기 :

postgres=# show pool_nodes;
 node_id |    hostname     | port | status | lb_weight |  role   
---------+-----------------+------+--------+-----------+---------
 0       | 192.168.100.140 | 5432 | 2      | 0.500000  | primary
 1       | 192.168.100.142 | 5432 | 2      | 0.500000  | standby
(2 rows)

참고 : 상태가 2, 정상적인 연결 나타내며 상태 상태에로
     - 0의 상태는 초기화 중에 사용되기 때문에,이 상태를 표시하지 않습니다 show 명령을.
     1-- 노드는 시작했지만 연결되지되었습니다.
     2 - 노드가 시작, 연결이 있습니다.
     3 - 노드 아래로.

3.PCP 명령

1) 노드의 수를 구하는 (루트 사용자)

[root@master etc]# pcp_node_count 10 127.0.0.1 9898 postgres postgres

장소 :

  • 10 시간 제한
  • 127.0.0.1 서버에서 실행하기 때문에 pgpool-II는, 여기 127.0.0.1 사용될 IP 호스트이다. 또한 192.168.100.140 또는 192.168.100.142 사용할 수 있습니다
  • PCP 포트 번호 9898이 배치되어 pgpool.conf
  • 주치의에 대한 사용자 이름을 POSTGRES
  • pcp.conf의 구성에서 무엇보다도 사용자의 암호에 대한 포스트 그레스.

2) 노드 정보를 취득 (root 사용자)

[root@master etc]# pcp_node_info 10 127.0.0.1 9898 postgres postgres 0

pgpool-II에서 사용자의 3) 노드 (루트)

[root@master ~]# pcp_detach_node 10 127.0.0.1 9898 postgres postgres 1

pgpool-II의 슬레이브 노드에서 출발하는 명령. 분배에 연결된 노드에 데이터베이스 노드, 또는 원하지 않는 pgpool-II를 유지하기 위해 필요는 명령 pgpool-II에서 노드에 필요한 보통합니다.

4)) 노드 pgpool-II (root 사용자와 연관된

[root@master ~]# pcp_attach_node 10 127.0.0.1 9898 postgres postgres 1

pgpool-II에서 슬레이브 노드와 연관된 명령. 유지 보수가 완료하거나 새 노드를 추가 할 때, 노드는 pgpool-II에 추가 할 수 있습니다.

노드, 서버가 늦게 회복되는 경우에도, 시작 데이터베이스의 데이터베이스 오류 결과를 감지하면 데이터베이스를 수동으로 시작 호스트 때문에 나 또한, 필요가 작업을 수행 부착합니다. 동시에 필요는 노드가 두 개의 노드에서 연결 여부를 관찰합니다.

5) 온라인) 노드 (루트 사용자를 재개

[root@master ~]# pcp_recovery_node 10 127.0.0.1 9898 postgres postgres 1

데이터베이스가 손상되면, 새로운 노드를 추가하는 경우 동기화, 노드의 복구에 대한 필요성을 필요로한다.

마스터 노드 넘어진 경우, 매개 변수에 기초 pgpool-II failover_command는 장애 슬레이브 노드 기반 트리거를 수행한다.

이 경우 모든 세션은 마스터 노드에 다시 연결합니다. 마스터를 복원해야하는 경우, 당신은 명령을 사용할 수 있습니다 :

[root@master ~]# pcp_recovery_node 10 127.0.0.1 9898 postgres postgres 0

마스터 노드에서 같은 성공적인 구현 및 슬레이브 후 새 마스터 노드입니다.

로드 균형 조정

다음과 같이 pgpool 1. 연결은 두 개의 레코드를 삽입, 테이블을 만들 :

postgres=# create table test01(id int,note text);
CREATE TABLE
postgres=# insert into test01 values(1,'11111');
INSERT 0 1
postgres=# insert into test01 values(2,'22222');
INSERT 0 1

2. 연결 pgpool는 노드가 반환되는 데이터를 구분 플러스 기능 "pg_postmaster_start_time"하기 위해, 두 서버에서 쿼리 테이블 "test01"앞에 지어졌다.

192.168.100.140에서 다음 명령을 실행합니다 :

postgres=# select pg_postmaster_start_time(), * from test01;
   pg_postmaster_start_time    | id | note  
-------------------------------+----+-------
 2017-05-08 13:17:32.135454+08 |  1 | 11111
 2017-05-08 13:17:32.135454+08 |  2 | 22222
(2 rows)

192.168.100.142에서 다음 명령을 실행합니다 :

postgres=# select pg_postmaster_start_time(), * from test01;
   pg_postmaster_start_time    | id | note  
-------------------------------+----+-------
 2017-05-08 13:16:39.570439+08 |  1 | 11111
 2017-05-08 13:16:39.570439+08 |  2 | 22222
(2 rows)

우리는로드 밸런싱이 제대로 작동 할 수 있습니다 볼 수 있습니다.

장애 조치

주요 결함은 주 서버가 실패 할 경우 신속하게 백업 서버에 트리거 파일을 만들 전환 할 때, 파일을 올릴 트리거의 검출시 대기 데이터베이스가 읽기 전용 일반 전경 응용 프로그램을 제공하기 위해 계속 이렇게 같이 읽기 - 쓰기 모드 서비스를 제공합니다.

구성 파일 pgpool.conf에 따르면 failover_command 구성 항목은 같은 다음, / usr / 지방 / pgpool / etc 디렉토리 아래의 스크립트 failover.sh 쓰기 :

failed_node=$1
new_master=$2
trigger_file=$3

# Do nothing if standby goes down.
if [ $failed_node = 1 ]; then
        exit 0;
fi

# Create the trigger file.
/usr/bin/ssh -T $new_master /bin/touch $trigger_file

exit 0

스크립트에 실행 권한 :

[postgres@master etc]$ chmod 755 failover.sh

파일이 슬레이브 서버 trigger_file에서 생성 여부를 기본 데이터베이스가 마스터 서버에서 실행 명령에서 스위치에 제대로 스크립트를 작동 감지되었는지 확인

마스터 쉘 스크립트 실행에 :

[postgres@master etc]$ ./failover.sh 0 192.168.100.142 /usr/local/pgsql/trigger_file

파일에 생성 trigger_file 슬레이브 검사로 전환 / usr / 지방 /의 pgSQL의

이제 우리는 주 서버가 마스터 이상에서 실행, 정지 시뮬레이션 :

[postgres@master etc]$ pg_ctl stop

슬레이브 노드 연결 정보 참조를 Pgpool :

postgres=# show pool_nodes;
 node_id |    hostname     | port | status | lb_weight |  role   
---------+-----------------+------+--------+-----------+---------
 0       | 192.168.100.140 | 5432 | 3      | 0.500000  | standby
 1       | 192.168.100.142 | 5432 | 2      | 0.500000  | primary
(2 rows)

대기 모드 전환이 이미 완료 볼 수 있습니다.

이때, 원래의 기본 라이브러리 데이터베이스 대기 스위치 상태는 3이다. 새로운 중앙 도서관 문에 연결된 노드를 실행합니다 :

[root@slave ~]# pcp_attach_node 10 127.0.0.1 9898 postgres postgres 0

노드 정보보기 :

postgres=# show pool_nodes;
 node_id |    hostname     | port | status | lb_weight |  role   
---------+-----------------+------+--------+-----------+---------
 0       | 192.168.100.140 | 5432 | 1      | 0.500000  | standby
 1       | 192.168.100.142 | 5432 | 2      | 0.500000  | primary
(2 rows)
게시 17 개 원래 기사 · 원 찬양 2 ·은 50000 +를 볼

추천

출처blog.csdn.net/u011250186/article/details/103767032