pgbouncer使用及配置介绍

介绍

postgres使用fork进程的方式来处理每个连接请求,本身没有连接池的概念,所以在有大量连接的业务场景中(特别是短连接较多),会在前端架设一个连接池。
目前pg主流的连接池主要有pgpool和pgbouncer。而相对于pgpool,pgbouncer较为轻量级,支持的功能也相对较少。

对比pgpool

相对与pgpool,pgbouncer对资源的需求更小,如果你仅仅只需要一个连接池的功能,选择pgbouncer是正确的。但是如果你还需要一下故障切换,负载均衡,同步的功能,pgpool更适合。

安装

官网下载源码包:

$ ./configure --prefix=/usr/local --with-libevent=libevent-prefix
$ make
$ make install

注意:需要安装libevent-devel openssl-devel两个依赖包。

三种连接模式

Session pooling
Most polite method. When client connects, a server connection will be assigned to it for the whole duration the client stays connected. When the client disconnects, the server connection will be put back into the pool. This is the default method.

Transaction pooling
A server connection is assigned to client only during a transaction. When PgBouncer notices that transaction is over, the server connection will be put back into the pool.

Statement pooling
Most aggressive method. The server connection will be put back into pool immediately after a query completes. Multi-statement transactions are disallowed in this mode as they would break.

区分这几个模式是何时在回收连接,在会话结束后回收,事务结束后回收,sql语句执行之后回收。默认的选项是session。建议还是修改成transaction比较好,具体原因可以参考这篇文章

example config

[databases]
template1 = host=127.0.0.1 port=5432 dbname=template1

[pgbouncer]
listen_port = 6543
listen_addr = 127.0.0.1
auth_type = md5
auth_file = users.txt
logfile = pgbouncer.log
pidfile = pgbouncer.pid
admin_users = someuser

创建文件pgbouncer.ini
其中databases地址写的是实际的postgresql连接地址
第二个是pgbouncer的配置,登陆用户帐号密码需要写在另一个文件users.txt里面。
格式:

"someuser" "same_password_as_in_server"

启动

pgbouncer -d pgbouncer.ini
会在当前目录下生成log和pid文件,其中pid文件记录的是pgbouncer的pid,停止程序时直接用kill。

连接到数据库

psql -p 6543 -U someuser template1

连接到pgbouncer

psql -p 6543 -U someuser pgbouncer

这个模式下可以查看一些pgbouncer参数信息。
show help
show stats
show servers
show clients
show pools

链接

link
link
link

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值