Files
mayfly-go/server/internal/mongo/mgm/conn_cache.go
meilin.huang 778cb7f4de reafctor: pool
2025-05-22 23:29:50 +08:00

36 lines
837 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package mgm
import (
"context"
"mayfly-go/pkg/pool"
)
var (
poolGroup = pool.NewPoolGroup[*MongoConn]()
)
// 从缓存中获取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()
if err != nil {
return nil, err
}
// 连接mongo
return mi.Conn()
})
if err != nil {
return nil, err
}
// 从连接池中获取一个可用的连接
return pool.Get(ctx)
}
// 关闭连接,并移除缓存连接
func CloseConn(mongoId uint64) {
poolGroup.Close(getConnId(mongoId))
}