connpool

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2022 License: MIT Imports: 7 Imported by: 0

README

connpool

GoDoc Go Report Card

介绍

一个面向所有可复用链接的连接池。

特性

  • 提供连接池最基本的功能,包括核心连接数,最大连接数,链接最大空闲时间,等待超时等
  • 提供连接重试功能,包括定时重试,指数退避重试
  • 允许在连接失败超过一定次数或时间后剔除连接地址
  • 允许动态注入连接地址
  • 允许自定义WarmUp功能

安装

go get github.com/emove/connpool

示例

快速开始
import (
    "fmt"
    "net"
    
    "github.com/emove/connpool"
)

func main() {
    // 创建一个连接池,传入三个基本参数
    // 连接地址,创建链接的方法,关闭链接的方法
    pool := connpool.NewPool([]string{addr}, dial, close,
        connpool.CoreNums(5), // 配置单个地址链接的核心连接数,默认配置为1
        connpool.MaxNums(20), // 配置单个地址链接的最大连接数,默认配置为10
        connpool.MaxIdleTime(10*time.Second), // 配置链接的最大空闲时间,默认配置为30秒
        connpool.WaitTimeout(5*time.Second), // 配置获取链接的超时时间,默认配置为3秒
    )
    con, err := pool.Get()
    if err != nil {
        fmt.Printf("get connection err: %v\n", err)
        return
    }
    
    conn := con.(net.Conn)
    _, err = conn.Write([]byte("hello world"))
    if err != nil {
        // 使用中发生错误,交由连接池销毁该连接
        pool.Discard(con)
    } else {
        // 将可用链接归还给连接池,等待复用
        pool.Put(con)
    }
    
    // 关闭连接池
    pool.Close()
}


// 定义连接函数,创建并返回一个tcp连接
func dial(addr string) (interface{}, error) {
    return net.Dial("tcp", addr)
}

// 定义连接关闭函数
func close(con interface{}) {
    if c, ok := con.(net.Conn); ok {
    	_ = c.Close()
    }
}
更多用法

connpool-example

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotUsableAddr represents all addresses has been eliminated from pool
	ErrNotUsableAddr = errors.New("not usable addr")
	// ErrPoolClosed represents the pool has been closed
	ErrPoolClosed = errors.New("pool closed")
	// ErrGetConnWaitTimeout represents get connection from pool timeout
	ErrGetConnWaitTimeout = errors.New("get connection wait timeout")
	// ErrIllegalAddress represents the specific address does not registered before pool.Get() called
	ErrIllegalAddress = errors.New("unknown address")
	// ErrAddrEliminated represents the address was eliminated
	ErrAddrEliminated = errors.New("address has been eliminated")
)

Functions

This section is empty.

Types

type Close

type Close = func(interface{})

Close is a connection closed hook.

type ConnPool

type ConnPool interface {
	Get(addr ...string) (interface{}, error)
	Put(interface{})
	Discard(interface{})
	Close()
}

ConnPool is an interface

func NewPool

func NewPool(addrs []string, d Dial, closer Close, ops ...Option) ConnPool

NewPool returns a ConnPool

type Connection

type Connection interface {
	Value(k interface{}) interface{}
	WithValue(k, v interface{})
}

Connection is used to attach some information to the connection to relieve the pressure of the pool. Implements it to gain a better performance when the pool working in a heavily load. For example:

type Conn struct {
	ctx context.Context
}

func (c *Conn) Value(k interface{}) interface{} {
	return c.ctx.Value(k)
}

func (c *Conn) WithValue(k, v interface{}) {
	c.ctx = context.WithValue(c.ctx, k, v)
}

type Dial

type Dial = func(addr string) (interface{}, error)

Dial is used to create new connections.

type EliminatedHook

type EliminatedHook = func(addr string)

type Option

type Option func(p *pool)

Option pool option

func CoreNums

func CoreNums(nums int) Option

CoreNums sets how many connections should be initial of per address

func DialBackoffPolicy

func DialBackoffPolicy(policy backoff.Policy) Option

DialBackoffPolicy sets the backoff policy for dial error

func EliminateAddr

func EliminateAddr(maxErrorTimes int, maxErrorPeriod time.Duration, hook EliminatedHook) Option

EliminateAddr eliminates the address from pool when an address dial error times greater than maxErrorTimes or continuous error duration greater than maxErrorPeriod

func Lazy

func Lazy() Option

Lazy dials only when in need

func MaxIdleTime

func MaxIdleTime(d time.Duration) Option

MaxIdleTime sets a duration before an idle connection would be closed

func MaxNums

func MaxNums(nums int) Option

MaxNums sets max connection number of per address

func MaxWaitingCapacity

func MaxWaitingCapacity(nums int) Option

MaxWaitingCapacity sets waiting request channel capacity

func WaitTimeout

func WaitTimeout(d time.Duration) Option

WaitTimeout sets max waiting time when get connection from pool

func WithWarmUp

func WithWarmUp(wu WarmUp) Option

WithWarmUp sets warm up func to control the warming up connection pool

type Registrar

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

Registrar used to register new addrs to the pool

func NewRegistrar

func NewRegistrar(cp ConnPool) *Registrar

NewRegistrar returns a Registrar

func (*Registrar) Register

func (r *Registrar) Register(addrs ...string) error

Register registers addrs to the pool

type WarmUp

type WarmUp = func(waits, idles, actives, max uint32) uint32

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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