2023-10-27 17:41:45 +08:00
|
|
|
|
package mgm
|
|
|
|
|
|
|
|
|
|
|
|
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[*MongoConn]()
|
|
|
|
|
|
)
|
2025-05-21 04:42:30 +00:00
|
|
|
|
|
2025-05-26 22:33:51 +08:00
|
|
|
|
func init() {
|
|
|
|
|
|
mcm.AddCheckSshTunnelMachineUseFunc(func(machineId int) bool {
|
|
|
|
|
|
items := poolGroup.AllPool()
|
|
|
|
|
|
for _, v := range items {
|
2025-05-29 20:24:48 +08:00
|
|
|
|
conn, err := v.Get(context.Background(), pool.WithGetNoUpdateLastActive(), pool.WithGetNoNewConn())
|
2025-05-26 22:33:51 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
continue // 获取连接失败,跳过
|
|
|
|
|
|
}
|
|
|
|
|
|
if conn.Info.SshTunnelMachineId == machineId {
|
|
|
|
|
|
return true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return false
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-05-22 23:29:50 +08:00
|
|
|
|
// 从缓存中获取mongo连接信息, 若缓存中不存在则会使用回调函数获取mongoInfo进行连接并缓存
|
|
|
|
|
|
func GetMongoConn(ctx context.Context, mongoId uint64, getMongoInfo func() (*MongoInfo, error)) (*MongoConn, error) {
|
|
|
|
|
|
pool, err := poolGroup.GetCachePool(getConnId(mongoId), func() (*MongoConn, error) {
|
|
|
|
|
|
// 若缓存中不存在,则从回调函数中获取MongoInfo
|
|
|
|
|
|
mi, err := getMongoInfo()
|
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
|
|
|
|
// 连接mongo
|
|
|
|
|
|
return mi.Conn()
|
|
|
|
|
|
})
|
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 pool.Get(ctx)
|
2023-10-27 17:41:45 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 关闭连接,并移除缓存连接
|
|
|
|
|
|
func CloseConn(mongoId uint64) {
|
2025-05-22 23:29:50 +08:00
|
|
|
|
poolGroup.Close(getConnId(mongoId))
|
2023-10-27 17:41:45 +08:00
|
|
|
|
}
|