封装的方法类
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package connPoolx
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// 连接池
|
||||
|
||||
// 核心思想:连接放在这里面统一管理,所有的新建与删除需要外部操作
|
||||
|
||||
// 适用场景:每一个key对应一个val
|
||||
|
||||
type connPool struct {
|
||||
pool sync.Map
|
||||
}
|
||||
|
||||
type PoolValue interface {
|
||||
Close() error
|
||||
}
|
||||
|
||||
func NewConnPool() *connPool {
|
||||
return &connPool{}
|
||||
}
|
||||
|
||||
// 同名将覆盖
|
||||
func (c *connPool) Store(key string, value PoolValue) {
|
||||
c.pool.Store(key, value)
|
||||
}
|
||||
|
||||
func (c *connPool) Load(key string) (value PoolValue, ok bool) {
|
||||
val, ok := c.pool.Load(key)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
value, ok = val.(PoolValue)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return value, true
|
||||
}
|
||||
|
||||
func (c *connPool) Close(key string) error {
|
||||
val, ok := c.pool.LoadAndDelete(key)
|
||||
if ok {
|
||||
value, ok := val.(PoolValue)
|
||||
if !ok {
|
||||
return errors.New("解析异常")
|
||||
}
|
||||
return value.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *connPool) Range(f func(key any, value any) bool) {
|
||||
c.pool.Range(f)
|
||||
}
|
||||
Reference in New Issue
Block a user