2023-10-27 17:41:45 +08:00
|
|
|
|
package mgm
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
2025-10-18 03:15:25 +00:00
|
|
|
|
"fmt"
|
2023-10-27 17:41:45 +08:00
|
|
|
|
"mayfly-go/pkg/logx"
|
|
|
|
|
|
|
2025-06-22 10:52:06 +08:00
|
|
|
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
2023-10-27 17:41:45 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
type MongoConn struct {
|
|
|
|
|
|
Id string
|
|
|
|
|
|
Info *MongoInfo
|
|
|
|
|
|
|
|
|
|
|
|
Cli *mongo.Client
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-05-22 23:29:50 +08:00
|
|
|
|
/******************* pool.Conn impl *******************/
|
|
|
|
|
|
|
|
|
|
|
|
func (mc *MongoConn) Close() error {
|
2023-10-27 17:41:45 +08:00
|
|
|
|
if mc.Cli != nil {
|
|
|
|
|
|
if err := mc.Cli.Disconnect(context.Background()); err != nil {
|
|
|
|
|
|
logx.Errorf("关闭mongo实例[%s]连接失败: %s", mc.Id, err)
|
2025-05-22 23:29:50 +08:00
|
|
|
|
return err
|
2023-10-27 17:41:45 +08:00
|
|
|
|
}
|
|
|
|
|
|
mc.Cli = nil
|
|
|
|
|
|
}
|
2025-05-22 23:29:50 +08:00
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (mc *MongoConn) Ping() error {
|
2025-10-18 03:15:25 +00:00
|
|
|
|
// 首先检查mc是否为nil
|
|
|
|
|
|
if mc == nil {
|
|
|
|
|
|
return fmt.Errorf("mc connection is nil")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 然后检查mc.Cli是否为nil,这是避免空指针异常的关键
|
|
|
|
|
|
if mc.Cli == nil {
|
|
|
|
|
|
return fmt.Errorf("mc client is nil")
|
|
|
|
|
|
}
|
2025-05-22 23:29:50 +08:00
|
|
|
|
return mc.Cli.Ping(context.Background(), nil)
|
2023-10-27 17:41:45 +08:00
|
|
|
|
}
|