From 82edb3b320a12a38e5f8fa5db3ca5545990a40b2 Mon Sep 17 00:00:00 2001 From: zhangxin Date: Sun, 18 Apr 2021 17:25:11 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=8D=E5=90=8C=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E4=BD=BF=E7=94=A8=E4=B8=80=E4=B8=AAcollection?= =?UTF-8?q?=E5=8F=A5=E6=9F=84=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- infra/logger/mongo.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/infra/logger/mongo.go b/infra/logger/mongo.go index 9db2b8e..71a5004 100644 --- a/infra/logger/mongo.go +++ b/infra/logger/mongo.go @@ -5,14 +5,21 @@ import ( "fmt" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" + "strconv" "time" ) var ( - collection *mongo.Collection + collectionMap map[string]*mongo.Collection ) func NewMongoDriver(config db, level int) (driver, error) { + if collectionMap == nil { + collectionMap = make(map[string]*mongo.Collection) + } + var collection *mongo.Collection + mKey := config.Host + strconv.Itoa(config.Port) + config.Database + config.Table + collection = collectionMap[mKey] if collection == nil { ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) client, err := mongo.Connect(ctx, options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", config.Host, config.Port))) @@ -24,7 +31,9 @@ func NewMongoDriver(config db, level int) (driver, error) { return nil, err } collection = client.Database(config.Database).Collection(config.Table) + collectionMap[mKey] = collection } + return &mongoLogger{ level: level, collection: collection,