dbpool

package
v0.0.0-...-2824e21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2023 License: MIT Imports: 6 Imported by: 0

README

Database Connection Pool

这个包实现了数据库连接池。

特性

  • 设置最小和最大连接数
  • 连接重用,避免重复创建连接
  • 连接超时设置
  • 健康检查机制,关闭失效连接
  • 定期清理过期连接

用法

pool := dbpool.New(max, min, timeout)

pool.Open() 

conn, err := pool.Acquire()

// 使用连接

pool.Release(conn)

pool.Close()

接口

  • New 创建连接池,传入最大连接数、最小连接数和获取连接超时时间
  • Open 打开连接池,初始化连接
  • Acquire 获取一个连接
  • Release 释放使用完的连接
  • Close 关闭连接池
  • Cleaner 定期清理过期连接
  • Check 健康检查连接

实现

  • 使用channel管理连接池
  • 打开连接后放入连接池供重用
  • 获取连接时优先返回已有连接
  • 定期清理过期和失效连接
  • 小于最小连接数时打开新连接

TODO

  • 添加连接池统计和指标
  • 从配置文件初始化连接池
  • 连接泄漏检测

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConnectionPool

type ConnectionPool struct {

	// OpenConnection opens a new connection.
	OpenConnection func() (*DBConn, error)
	// contains filtered or unexported fields
}

ConnectionPool manages a pool of connections.

func New

func New(maxConnections, minConnections int, waitTimeout time.Duration) *ConnectionPool

New creates a new ConnectionPool.

func (*ConnectionPool) Acquire

func (p *ConnectionPool) Acquire() (*DBConn, error)

Acquire retrieves a connection from the pool.

func (*ConnectionPool) Check

func (p *ConnectionPool) Check(conn *DBConn) bool

Check returns true if connection is healthy.

func (*ConnectionPool) Cleaner

func (p *ConnectionPool) Cleaner()

CleanUpClosedConnections closes expired connections and opens new connections to maintain min connections.

func (*ConnectionPool) Close

func (p *ConnectionPool) Close()

Close closes the connection pool.

func (*ConnectionPool) CloseExpiredConnections

func (p *ConnectionPool) CloseExpiredConnections()

CloseExpiredConnections closes expired connections.

func (*ConnectionPool) MaintainMinConnections

func (p *ConnectionPool) MaintainMinConnections()

MaintainMinConnections opens connections if below min.

func (*ConnectionPool) Open

func (p *ConnectionPool) Open() error

Open initializes the connection pool.

func (*ConnectionPool) Release

func (p *ConnectionPool) Release(conn *DBConn)

Release puts a connection back into the pool.

type DBConn

type DBConn struct {
	DB        *sql.DB
	HeartBeat time.Time
	TimeOut   time.Duration
}

DBConn 封装数据库连接

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL