一、为什么要使用连接池
频繁的建立、关闭连接会降低系统性能
1)资源重用,减少开销
2)响应速度快
3)可根据预先设定好的超时,强制回收连接,避免资源泄露
二、实现
在内部对象池维护一定数量的数据库连接,对外暴露获取和放回的方法
Golang 的连接池实现在标准库 database/sql/sql.go 下
2.1 连接池的结构
1 | go复制代码type DB struct { |
2.2 获取连接
1 | go复制代码func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error) { |
2.3 释放连接
1 | go复制代码func (db *DB) putConn(dc *driverConn, err error, resetSession bool) { |
2.4 其它定义
1 | go复制代码type connReuseStrategy int8 |
三、使用
1 | erlang复制代码import ( |
本文转载自: 掘金