2023-10-27 17:41:45 +08:00
|
|
|
|
package rdm
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2025-05-21 04:42:30 +00:00
|
|
|
|
"context"
|
2025-05-26 22:33:51 +08:00
|
|
|
|
"mayfly-go/internal/machine/mcm"
|
2025-05-21 04:42:30 +00:00
|
|
|
|
"mayfly-go/pkg/pool"
|
2023-10-27 17:41:45 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-05-22 23:29:50 +08:00
|
|
|
|
var (
|
|
|
|
|
|
poolGroup = pool.NewPoolGroup[*RedisConn]()
|
|
|
|
|
|
)
|
2023-10-27 17:41:45 +08:00
|
|
|
|
|
2025-05-26 22:33:51 +08:00
|
|
|
|
func init() {
|
|
|
|
|
|
mcm.AddCheckSshTunnelMachineUseFunc(func(machineId int) bool {
|
|
|
|
|
|
// 遍历所有redis连接实例,若存在redis实例使用该ssh隧道机器,则返回true,表示还在使用中...
|
|
|
|
|
|
items := poolGroup.AllPool()
|
|
|
|
|
|
for _, v := range items {
|
|
|
|
|
|
if v.Stats().TotalConns == 0 {
|
|
|
|
|
|
continue // 连接池中没有连接,跳过
|
|
|
|
|
|
}
|
|
|
|
|
|
rc, err := v.Get(context.Background())
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
continue // 获取连接失败,跳过
|
|
|
|
|
|
}
|
|
|
|
|
|
if rc.Info.SshTunnelMachineId == machineId {
|
|
|
|
|
|
return true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return false
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-05-22 23:29:50 +08:00
|
|
|
|
// 从缓存中获取redis连接信息, 若缓存中不存在则会使用回调函数获取redisInfo进行连接并缓存
|
|
|
|
|
|
func GetRedisConn(ctx context.Context, redisId uint64, db int, getRedisInfo func() (*RedisInfo, error)) (*RedisConn, error) {
|
|
|
|
|
|
p, err := poolGroup.GetCachePool(getConnId(redisId, db), func() (*RedisConn, error) {
|
|
|
|
|
|
// 若缓存中不存在,则从回调函数中获取RedisInfo
|
|
|
|
|
|
ri, err := getRedisInfo()
|
2025-05-21 04:42:30 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
2023-10-27 17:41:45 +08:00
|
|
|
|
}
|
2025-05-22 23:29:50 +08:00
|
|
|
|
// 连接数据库
|
|
|
|
|
|
return ri.Conn()
|
|
|
|
|
|
})
|
2025-05-21 04:42:30 +00:00
|
|
|
|
|
2023-10-27 17:41:45 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-05-21 04:42:30 +00:00
|
|
|
|
// 从连接池中获取一个可用的连接
|
2025-05-22 23:29:50 +08:00
|
|
|
|
return p.Get(ctx)
|
2023-10-27 17:41:45 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 移除redis连接缓存并关闭redis连接
|
|
|
|
|
|
func CloseConn(id uint64, db int) {
|
2025-05-22 23:29:50 +08:00
|
|
|
|
poolGroup.Close(getConnId(id, db))
|
2023-10-27 17:41:45 +08:00
|
|
|
|
}
|