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

46 lines
1012 B
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
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 {
pool.Close()
}
}
2024-02-23 22:53:17 +08:00
}