Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
class100 committed Apr 26, 2021
1 parent a3a5114 commit 6a89349
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
8 changes: 8 additions & 0 deletions xmongo/new_mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import (
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"sync"
"time"
)

var (
client *mongo.Client
mongoDB *mongo.Database
mongoLock = &sync.RWMutex{}
)

type MongoConf struct {
Expand All @@ -24,6 +26,8 @@ func InitMongoDB(conf *MongoConf) error {
return errors.New("conf param invalid")
}

mongoLock.Lock()
defer mongoLock.Unlock()
client, err := mongo.NewClient(options.Client().ApplyURI(conf.Url))
if err != nil {
return errors.WithStack(err)
Expand All @@ -45,6 +49,8 @@ type MongoCollection struct {
}

func NewMongoCollection(coll string) *MongoCollection {
mongoLock.RLock()
defer mongoLock.RUnlock()
return &MongoCollection{mongoDB.Collection(coll)}
}

Expand All @@ -53,5 +59,7 @@ func CloseMongo() error {
return errors.New("mongo client invalid")
}

mongoLock.RLock()
defer mongoLock.RUnlock()
return client.Disconnect(context.TODO())
}
14 changes: 9 additions & 5 deletions xmysql/new_mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@ import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"sync"
)

var newMysqlPools = make(map[string]*gorm.DB)
var (
newMysqlPools = make(map[string]*gorm.DB)
mysqlLock = &sync.RWMutex{}
)

func InitMySql(configs []*MySqlPoolConfig) error {
for _, c := range configs {
Expand All @@ -21,7 +25,7 @@ func InitMySql(configs []*MySqlPoolConfig) error {
if err != nil {
return errors.New(fmt.Sprintf("mysql pool %s error %v", xjson.SafeMarshal(c), err))
}
xsync.WithLock(mysqlPoolLock, func() {
xsync.WithLock(mysqlLock, func() {
newMysqlPools[c.Alias] = p
})
}
Expand Down Expand Up @@ -51,13 +55,13 @@ func createNewMySqlPool(c *MySqlPoolConfig) (*gorm.DB, error) {
}

func GetMySqlConn(alias string) *gorm.DB {
mysqlPoolLock.RLock()
defer mysqlPoolLock.RUnlock()
mysqlLock.RLock()
defer mysqlLock.RUnlock()
return newMysqlPools[alias]
}

func CloseMysql() {
xsync.WithLock(mysqlPoolLock, func() {
xsync.WithLock(mysqlLock, func() {
for _, db := range newMysqlPools {
if db == nil {
continue
Expand Down

0 comments on commit 6a89349

Please sign in to comment.