github.com/songzhibin97/gkit@v1.2.13/container/pool/pool.go (about) 1 package pool 2 3 import ( 4 "context" 5 "errors" 6 "time" 7 8 "github.com/songzhibin97/gkit/options" 9 ) 10 11 // package pool: 连接池 12 const ( 13 minDuration = 100 * time.Millisecond 14 ) 15 16 var ( 17 ErrPoolNewFuncIsNull = errors.New("container/pool: 初始化函数为空") 18 // ErrPoolExhausted 连接以耗尽 19 ErrPoolExhausted = errors.New("container/pool: 连接已耗尽") 20 // ErrPoolClosed 连接池已关闭. 21 ErrPoolClosed = errors.New("container/pool: 连接池已关闭") 22 23 // nowFunc: 返回当前时间 24 nowFunc = time.Now 25 ) 26 27 type IShutdown interface { 28 Shutdown() error 29 } 30 31 // Pool interface. 32 type Pool interface { 33 New(f func(ctx context.Context) (IShutdown, error)) 34 Get(ctx context.Context) (IShutdown, error) 35 Put(ctx context.Context, c IShutdown, forceClose bool) error 36 Shutdown() error 37 } 38 39 // config Pool 选项 40 type config struct { 41 // active: 池中的连接数, 如果为 == 0 则无限制 42 active uint64 43 44 // idle 最大空闲数 45 idle uint64 46 47 // idleTimeout 空闲等待的时间 48 idleTimeout time.Duration 49 50 // waitTimeout 如果设置 waitTimeout 如果池内资源已经耗尽,将会等待 time.Duration 时间, 直到某个连接退回 51 waitTimeout time.Duration 52 53 // wait 如果是 true 则等待 waitTimeout 时间, 否则无线傻等 54 wait bool 55 } 56 57 // item: 58 type item struct { 59 createdAt time.Time 60 s IShutdown 61 } 62 63 // expire 是否到期 64 func (i *item) expire(timeout time.Duration) bool { 65 if timeout <= 0 { 66 return false 67 } 68 return i.createdAt.Add(timeout).Before(nowFunc()) 69 } 70 71 // shutdown 关闭 72 func (i *item) shutdown() error { 73 return i.s.Shutdown() 74 } 75 76 // defaultConfig 默认配置 77 func defaultConfig() *config { 78 return &config{ 79 active: 20, 80 idle: 10, 81 idleTimeout: 90 * time.Second, 82 waitTimeout: 0, 83 wait: false, 84 } 85 } 86 87 // Option选项 88 89 // SetActive 设置 Pool 连接数, 如果 == 0 则无限制 90 func SetActive(active uint64) options.Option { 91 return func(c interface{}) { 92 c.(*config).active = active 93 } 94 } 95 96 // SetIdle 设置最大空闲连接数 97 func SetIdle(idle uint64) options.Option { 98 return func(c interface{}) { 99 c.(*config).idle = idle 100 } 101 } 102 103 // SetIdleTimeout 设置空闲等待时间 104 func SetIdleTimeout(idleTimeout time.Duration) options.Option { 105 return func(c interface{}) { 106 c.(*config).idleTimeout = idleTimeout 107 } 108 } 109 110 // SetWait 设置期望等待 111 func SetWait(wait bool, waitTimeout time.Duration) options.Option { 112 return func(c interface{}) { 113 conf := c.(*config) 114 conf.wait = wait 115 conf.waitTimeout = waitTimeout 116 } 117 }