mirror of
https://gitee.com/dromara/mayfly-go
synced 2025-11-03 16:00:25 +08:00
36 lines
837 B
Go
36 lines
837 B
Go
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))
|
||
}
|