Files
connpoolx/simple/connPoolx.go
T
2026-05-03 22:37:59 +08:00

60 lines
997 B
Go

package simple
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)
}