easypool

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2022 License: MIT Imports: 6 Imported by: 3

README

Build Status

easypool

tcp连接池,最初是为easyss设计,作为其tcp连接池管理使用。 也可用于其他需要tcp连接池的场景。

特性

  • TCP连接池
  • 支持基于时间的优先队列,越早创建和使用的连接,越早从Pool中取出
  • 支持连接生命周期(最大空闲连接,连接最大存活时间等)

基本用法

factory := func() (net.Conn, error) { return net.Dial("tcp", "localhost:7777") }
config := &PoolConfig{
	InitialCap:  5,
	MaxCap:      20,
	MaxIdle:     5,
	Idletime:    10 * time.Second,
	MaxLifetime: 10 * time.Minute,
	Factory:     factory,
}

pool, err := NewHeapPool(config)
if err != nil {
	log.Printf("err:%v\n", err)
	return
}

conn, err := pool.Get()
if err != nil {
	log.Printf("err:%v\n", err)
	return
}

// do sth... with conn
// 使用完连接之后,调用Close发放,当前连接会重新放回到pool中
conn.Close()

// 如果需要直接关闭底层连接(比如底层连接已经失效),则:
conn.(*PoolConn).MarkUnusable()
conn.Close()

// 调用MarkUnusable()后,会返回true
conn.(*PoolConn).IsUnusable()

// 释放当前连接池中所有连接
pool.Close()

// 查看连接池中连接的个数
pool.Len()

License

The MIT License (MIT)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrClosed        = errors.New("pool is closed")
	ErrConfigInvalid = errors.New("config is invalid")
)

Functions

This section is empty.

Types

type Pool

type Pool interface {
	// Get return a new item from the pool. Closing the item puts it back to the pool
	Get() (net.Conn, error)
	// Close close the pool and release all resources
	Close()
	// Len returns the number of items of the pool
	Len() int
}

func NewHeapPool

func NewHeapPool(config *PoolConfig) (Pool, error)

type PoolConfig

type PoolConfig struct {
	InitialCap  int
	MaxCap      int
	MaxIdle     int
	Idletime    time.Duration
	MaxLifetime time.Duration
	Factory     func() (net.Conn, error)
}

type PoolConn

type PoolConn struct {
	net.Conn
	// contains filtered or unexported fields
}

func (*PoolConn) Close

func (pc *PoolConn) Close() error

Close put the connection back to pool if possible. Executed by multi times is ok.

func (*PoolConn) IsUnusable

func (pc *PoolConn) IsUnusable() bool

func (*PoolConn) MarkUnusable

func (pc *PoolConn) MarkUnusable()

type PriorityQueue

type PriorityQueue []*PoolConn

func (PriorityQueue) Len

func (pq PriorityQueue) Len() int

func (PriorityQueue) Less

func (pq PriorityQueue) Less(i, j int) bool

func (*PriorityQueue) Pop

func (pq *PriorityQueue) Pop() interface{}

func (*PriorityQueue) Push

func (pq *PriorityQueue) Push(x interface{})

func (PriorityQueue) Swap

func (pq PriorityQueue) Swap(i, j int)

Jump to

Keyboard shortcuts

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