今天学习了下PgBouncer的使用, PgBouncer可以在后端数据库和前端应用间建立连接的桥梁,由PgBouncer去处理和后端数据库的连接关系。 对客户端连接进行限制,预防过多或者恶意的连接请求。
PgBouncer 的特点
- 内存消耗低(默认为2k/连接),因为Bouncer不需要每次都接受完整的数据包
- 可以把不同的数据库连接到一个机器上,而对客户端保持透明
- 支持在线的重新配置而无须重启
- 仅支持V3协议,因此后端版本须>=7.4
以下是Pgbouncer的安装过程。
安装准备
下载源文件
http://pgfoundry.org/frs/?group_id=1000258&release_id=1645
安装libevent组件
http://monkey.org/~provos/libevent/下载,安装过程查看手册。
安装 PgBouncer
1 | ./configure --prefix=/opt/pgbouncer --with-libevent=/usr/local/ |
配置 PgBouncer
编写配置文件1
2
3$ mkdir -p $PGDATA/pgbouncer_config
$ mkdir -p $PGDATA/pgbouncer_config/run
cd $PGDATA/pgbouncer_config
配置文件 config.ini1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22[databases]
skytf = host=127.0.0.1 dbname=mydb port=1999 pool_size=500
postgres = host=127.0.0.1 dbname=postgres port=1999 pool_size=25
[pgbouncer]
pool_mode = session
listen_port = 1999
listen_addr = *
unix_socket_dir = /database/pgdata/pg_root/pgbouncer_config/run
auth_type = md5
auth_file = /database/pgdata/pg_root/pgbouncer_config/users.txt
logfile = /var/applog/pg_log/pgbouncer.log
#logfile = /dev/null
pidfile = /database/pgdata/pg_root/pgbouncer_config/pgbouncer.pid
max_client_conn = 6500
default_pool_size = 900
reserve_pool_timeout = 0
reserve_pool_size = 30
server_reset_query = DISCARD ALL;
admin_users = pgbouncer_admin
stats_users = pgbouncer_guest
ignore_startup_parameters = extra_float_digits,application_name,geqo
stats_period = 30
说明: 关于参数的解释在pgbouncer的源文件中有非常详细的文档,这里就不说明了。
配置文件 users.txt1
2"pgbouncer_admin" "pgbouncer_admin"
"skytf" "skytf"
启动 PgBouncer
1 | ./opt/pgbouncer/bin/pgbouncer -d /database/pgdata/pg_root/pgbouncer_config/config.ini |
测试通过pgbouncer连接是否正常1
psql -h 127.0.0.1 -p 1999 -d mydb -U skytf
管理 PgBouncer
以管理用户进入pgbouncer1
psql -h 127.0.0.1 -p 1999 -U pgbouncer_admin -d pgbouncer
查看pgbouncer运行情况1
2
3
4pgbouncer=# show stats;
pgbouncer=# show lists;
pgbouncer=# show pools;
pgbouncer=# show databases;
参考目录结构1
2
3
4
5
6[postgres@pg1 pgbouncer_config]$ ll
总计 16K
-rw-rw-r-- 1 postgres postgres 734 08-19 13:47 config.ini
-rw-r--r-- 1 postgres postgres 5 08-19 14:01 pgbouncer.pid
drwxrwxr-x 2 postgres postgres 4.0K 08-19 14:01 run
-rw-rw-r-- 1 postgres postgres 52 08-19 14:09 users.txt