123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- package init_serve
- import (
- "context"
- "github.com/qiniu/qmgo"
- "github.com/qiniu/qmgo/options"
- "go.mongodb.org/mongo-driver/bson"
- "go.mongodb.org/mongo-driver/event"
- mgoptions "go.mongodb.org/mongo-driver/mongo/options"
- "hongze/hongze_yb/global"
- "sync"
- )
- var (
- ConnectTimeoutMS = int64(3000)
- SocketTimeoutMS = int64(500000)
- MaxPoolSize = uint64(50)
- MinPoolSize = uint64(0)
- )
- func MgoNewClient() *qmgo.Client {
-
-
- mgoConfig := global.CONFIG.Mongo
- startedCommands := sync.Map{}
- cmdMonitor := &event.CommandMonitor{
- Started: func(_ context.Context, evt *event.CommandStartedEvent) {
- startedCommands.Store(evt.RequestID, evt.Command)
-
- },
- Succeeded: func(_ context.Context, evt *event.CommandSucceededEvent) {
-
-
-
-
- var commands bson.Raw
- v, ok := startedCommands.Load(evt.RequestID)
- if ok {
- commands = v.(bson.Raw)
- }
-
- global.MONGO_LOG.Info("\n【MongoDB】[%.3fms] [%v] \n", float64(evt.Duration)/1e6, commands)
- },
- Failed: func(_ context.Context, evt *event.CommandFailedEvent) {
-
-
-
-
- var commands bson.Raw
- v, ok := startedCommands.Load(evt.RequestID)
- if ok {
- commands = v.(bson.Raw)
- }
- global.MONGO_LOG.Info("\n【MongoDB】[%.3fms] [%v] \n %v \n", float64(evt.Duration)/1e6, commands, evt.Failure)
- },
- }
-
- ops := options.ClientOptions{ClientOptions: &mgoptions.ClientOptions{}}
- ops.SetMonitor(cmdMonitor)
- ctx := context.Background()
-
-
- client, err := qmgo.NewClient(ctx, &qmgo.Config{
- Uri: mgoConfig.Url,
- Auth: &qmgo.Credential{
- AuthMechanism: mgoConfig.AuthMechanism,
- AuthSource: mgoConfig.AuthSource,
- Username: mgoConfig.Username,
- Password: mgoConfig.Password,
-
- },
- Database: mgoConfig.Database,
- ConnectTimeoutMS: &ConnectTimeoutMS,
- SocketTimeoutMS: &SocketTimeoutMS,
- MaxPoolSize: &MaxPoolSize,
- MinPoolSize: &MinPoolSize,
- }, ops)
- if err != nil {
- panic("MongoDB连接异常:" + err.Error())
- }
- return client
- }
- func MgoGetColl(collName string) (cli *qmgo.QmgoClient, err error) {
- ctx := context.Background()
- config := &qmgo.Config{
-
-
- Coll: collName,
- ConnectTimeoutMS: &ConnectTimeoutMS,
- SocketTimeoutMS: &SocketTimeoutMS,
- MaxPoolSize: &MaxPoolSize,
- MinPoolSize: &MinPoolSize,
- }
- cli, err = qmgo.Open(ctx, config)
- return
- }
- func InitMongo() {
- if global.CONFIG.Mongo.Url != `` {
- mgoCli := MgoNewClient()
- global.MgoDataCli = mgoCli
- }
- }
|