gitee.com/woood2/luca@v1.0.4/internal/db/mongo.go (about) 1 package db 2 3 import ( 4 "context" 5 "fmt" 6 "gitee.com/woood2/luca/internal/conf" 7 "go.mongodb.org/mongo-driver/mongo" 8 "go.mongodb.org/mongo-driver/mongo/options" 9 "log" 10 "time" 11 ) 12 13 var globalMongoDB *mongo.Database 14 15 func SetMongoDB(db *mongo.Database) { 16 globalMongoDB = db 17 } 18 19 func MongoDB() *mongo.Database { 20 return globalMongoDB 21 } 22 23 func NewMongoDB(c *conf.Mongo) *mongo.Database { 24 uri := fmt.Sprintf("mongodb://%s:%s@%s:%d/%s?authSource=admin", c.User, c.Pwd, c.Host, c.Port, c.DB) 25 o := options.Client().ApplyURI(uri) 26 o.SetMaxPoolSize(uint64(c.MaxPoolSize)) //The default is 100. If this is 0, it will be set to math.MaxInt64. 27 o.SetMinPoolSize(uint64(c.MinPoolSize)) //The default is 0. 28 o.SetMaxConnIdleTime(5 * time.Minute) //The default is 0, meaning a connection can remain unused indefinitely. 29 ctxC, cancelC := context.WithTimeout(context.Background(), 5*time.Second) 30 defer cancelC() 31 client, err := mongo.Connect(ctxC, o) 32 if err != nil { 33 log.Panicln(err) 34 } 35 ctxP, cancelP := context.WithTimeout(context.Background(), 2*time.Second) 36 defer cancelP() 37 err = client.Ping(ctxP, nil) 38 if err != nil { 39 log.Panicln(err) 40 } 41 return client.Database(c.DB) 42 }