pool

package
v1.1.9 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2021 License: Apache-2.0 Imports: 4 Imported by: 0

README

pool

Golang 实现的连接池

功能:

  • 连接池中连接类型为interface{},使得更加通用
  • 连接的最大空闲时间,超时的连接将关闭丢弃,可避免空闲时连接自动失效问题
  • 支持用户设定 ping 方法,检查连接的连通性,无效的连接将丢弃
  • 使用channel处理池中的连接,高效

基本用法


//factory 创建连接的方法
factory := func() (interface{}, error) { return net.Dial("tcp", "127.0.0.1:4000") }

//close 关闭连接的方法
close := func(v interface{}) error { return v.(net.Conn).Close() }

//ping 检测连接的方法
//ping := func(v interface{}) error { return nil }

//创建一个连接池: 初始化5,最大连接30
poolConfig := &pool.PoolConfig{
	InitialCap: 5,
	MaxCap:     30,
	Factory:    factory,
	Close:      close,
	//Ping:       ping,
	//连接最大空闲时间,超过该时间的连接 将会关闭,可避免空闲时连接EOF,自动失效的问题
	IdleTimeout: 15 * time.Second,
}
p, err := pool.NewChannelPool(poolConfig)
if err != nil {
	fmt.Println("err=", err)
}

//从连接池中取得一个连接
v, err := p.Get()

//do something
//conn=v.(net.Conn)

//将连接放回连接池中
p.Put(v)

//释放连接池中的所有连接
p.Release()

//查看当前连接中的数量
current := p.Len()


注:

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	//ErrClosed 连接池已经关闭Error
	ErrClosed = errors.New("pool is closed")
)

Functions

This section is empty.

Types

type ChannelPool

type ChannelPool struct {
	// contains filtered or unexported fields
}

ChannelPool 存放连接信息

func (*ChannelPool) Close

func (c *ChannelPool) Close(conn interface{}) error

Close 关闭单条连接

func (*ChannelPool) Get

func (c *ChannelPool) Get() (interface{}, error)

Get 从pool中取一个连接

func (*ChannelPool) Len

func (c *ChannelPool) Len() int

Len 连接池中已有的连接

func (*ChannelPool) Ping

func (c *ChannelPool) Ping(conn interface{}) error

Ping 检查单条连接是否有效

func (*ChannelPool) Put

func (c *ChannelPool) Put(conn interface{}) error

Put 将连接放回pool中

func (*ChannelPool) Release

func (c *ChannelPool) Release()

Release 释放连接池中所有连接

type Pool

type Pool interface {
	Get() (interface{}, error)

	Put(interface{}) error

	Close(interface{}) error

	Release()

	Len() int
}

Pool 基本方法

func NewChannelPool

func NewChannelPool(poolConfig *PoolConfig) (Pool, error)

NewChannelPool 初始化连接

type PoolConfig

type PoolConfig struct {
	//连接池中拥有的最小连接数
	InitialCap int
	//连接池中拥有的最大的连接数
	MaxCap int
	//生成连接的方法
	Factory func() (interface{}, error)
	//关闭连接的方法
	Close func(interface{}) error
	//检查连接是否有效的方法
	Ping func(interface{}) error
	//连接最大空闲时间,超过该事件则将失效
	IdleTimeout time.Duration
}

PoolConfig 连接池相关配置

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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