Browse Source

修改不同配置使用一个collection句柄的bug

pull/119/head
zhangxin 3 years ago
parent
commit
82edb3b320
1 changed files with 10 additions and 1 deletions
  1. +10
    -1
      infra/logger/mongo.go

+ 10
- 1
infra/logger/mongo.go View File

@ -5,14 +5,21 @@ import (
"fmt" "fmt"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/options"
"strconv"
"time" "time"
) )
var ( var (
collection *mongo.Collection
collectionMap map[string]*mongo.Collection
) )
func NewMongoDriver(config db, level int) (driver, error) { 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 { if collection == nil {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) 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))) 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 return nil, err
} }
collection = client.Database(config.Database).Collection(config.Table) collection = client.Database(config.Database).Collection(config.Table)
collectionMap[mKey] = collection
} }
return &mongoLogger{ return &mongoLogger{
level: level, level: level,
collection: collection, collection: collection,


Loading…
Cancel
Save