介紹
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