Files
mayfly-go/server/internal/machine/mcm/client_cache.go

67 lines
1.6 KiB
Go
Raw Normal View History

2023-10-30 17:34:56 +08:00
package mcm
import (
2025-05-22 23:29:50 +08:00
"context"
"mayfly-go/pkg/pool"
2023-10-30 17:34:56 +08:00
)
2025-05-22 23:29:50 +08:00
var (
poolGroup = pool.NewPoolGroup[*Cli]()
)
2023-10-30 17:34:56 +08:00
func init() {
AddCheckSshTunnelMachineUseFunc(func(machineId int) bool {
// 遍历所有redis连接实例若存在redis实例使用该ssh隧道机器则返回true表示还在使用中...
items := poolGroup.AllPool()
for _, v := range items {
if v.Stats().TotalConns == 0 {
continue // 连接池中没有连接,跳过
}
cli, err := v.Get(context.Background())
if err != nil {
continue // 获取连接失败,跳过
}
sshTunnelMachine := cli.Info.SshTunnelMachine
if sshTunnelMachine != nil && sshTunnelMachine.Id == uint64(machineId) {
return true
}
}
return false
})
}
2025-05-22 23:29:50 +08:00
// 从缓存中获取客户端信息,不存在则回调获取机器信息函数,并新建。
// @param 机器的授权凭证名
func GetMachineCli(ctx context.Context, authCertName string, getMachine func(string) (*MachineInfo, error)) (*Cli, error) {
pool, err := poolGroup.GetCachePool(authCertName, func() (*Cli, error) {
mi, err := getMachine(authCertName)
if err != nil {
return nil, err
2023-10-30 17:34:56 +08:00
}
2025-05-22 23:29:50 +08:00
mi.Key = authCertName
2025-05-23 17:26:12 +08:00
return mi.Conn(context.Background())
2025-05-22 23:29:50 +08:00
})
2023-10-30 17:34:56 +08:00
if err != nil {
return nil, err
}
// 从连接池中获取一个可用的连接
2025-05-22 23:29:50 +08:00
return pool.Get(ctx)
}
2024-02-23 22:53:17 +08:00
// 删除指定机器缓存客户端,并关闭客户端连接
2023-10-30 17:34:56 +08:00
func DeleteCli(id uint64) {
2025-05-22 23:29:50 +08:00
for _, pool := range poolGroup.AllPool() {
2025-05-23 17:26:12 +08:00
if pool.Stats().TotalConns == 0 {
continue
}
conn, err := pool.Get(context.Background())
2025-05-22 23:29:50 +08:00
if err != nil {
continue
}
if conn.Info.Id == id {
poolGroup.Close(conn.Info.AuthCertName)
2025-05-22 23:29:50 +08:00
}
}
2024-02-23 22:53:17 +08:00
}