package mgodb import ( "context" "eta/eta_forum_admin/utils" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/event" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" "sync" "time" ) var ( MaxPoolSize = uint64(50) MinPoolSize = uint64(0) ) //func init() { // fmt.Println("start MgoNewClient") // MgoNewClient() // fmt.Println("end MgoNewClient") //} type MgoConfig struct { Url string `json:"url"` Username string `json:"username"` Password string `json:"password"` AuthMechanism string `json:"auth_mechanism"` Database string `json:"database"` } func NewMgoClient(mgoConfig MgoConfig) *mongo.Client { var err error ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() credential := options.Credential{ AuthMechanism: mgoConfig.AuthMechanism, Username: mgoConfig.Username, Password: mgoConfig.Password, } clientOpts := options.Client().ApplyURI(mgoConfig.Url).SetAuth(credential) startedCommands := sync.Map{} // map[int64]bson.Raw cmdMonitor := &event.CommandMonitor{ Started: func(_ context.Context, evt *event.CommandStartedEvent) { startedCommands.Store(evt.RequestID, evt.Command) //startedCommands[evt.RequestID] = evt.Command }, Succeeded: func(_ context.Context, evt *event.CommandSucceededEvent) { //log.Printf("Command: %v Reply: %v\n", // startedCommands[evt.RequestID], // evt.Reply, //) var commands bson.Raw v, ok := startedCommands.Load(evt.RequestID) if ok { commands = v.(bson.Raw) } utils.MongoLog.Info("\n【MongoDB】[%.3fms] [%v] \n", float64(evt.Duration)/1e6, commands) }, Failed: func(_ context.Context, evt *event.CommandFailedEvent) { //log.Printf("Command: %v Failure: %v\n", // startedCommands[evt.RequestID], // evt.Failure, //) var commands bson.Raw v, ok := startedCommands.Load(evt.RequestID) if ok { commands = v.(bson.Raw) } utils.MongoLog.Info("\n【MongoDB】[%.3fms] [%v] \n %v \n", float64(evt.Duration)/1e6, commands, evt.Failure) }, } // 创建options clientOpts.SetMonitor(cmdMonitor) clientOpts.SetMinPoolSize(MinPoolSize) clientOpts.SetMaxPoolSize(MaxPoolSize) clientOpts.SetConnectTimeout(10 * time.Second) mgoClient, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { panic(err) } if err = mgoClient.Ping(ctx, readpref.Primary()); err != nil { panic(err) } fmt.Println("Connected to MongoDB!") return mgoClient }