Browse Source

fix pooled db concurrency bug

pull/393/head
Goxiaoy 3 years ago
parent
commit
73ea0d02e7
  1. 34
      client/dtmcli/dtmimp/utils.go

34
client/dtmcli/dtmimp/utils.go

@ -151,21 +151,31 @@ func MayReplaceLocalhost(host string) string {
return host return host
} }
var sqlDbs sync.Map var sqlDbs = &mapCache{cache: map[string]*sql.DB{}}
// PooledDB get pooled sql.DB type mapCache struct {
func PooledDB(conf DBConf) (*sql.DB, error) { mutex sync.Mutex
cache map[string]*sql.DB
}
func (m *mapCache) LoadOrStore(conf DBConf, factory func(conf DBConf) (*sql.DB, error)) (*sql.DB, error) {
m.mutex.Lock()
defer m.mutex.Unlock()
dsn := GetDsn(conf) dsn := GetDsn(conf)
db, ok := sqlDbs.Load(dsn) if db, ok := m.cache[dsn]; ok {
if !ok { return db, nil
db2, err := StandaloneDB(conf)
if err != nil {
return nil, err
}
db = db2
sqlDbs.Store(dsn, db)
} }
return db.(*sql.DB), nil db, err := factory(conf)
if err != nil {
return nil, err
}
m.cache[dsn] = db
return db, nil
}
// PooledDB get pooled sql.DB
func PooledDB(conf DBConf) (*sql.DB, error) {
return sqlDbs.LoadOrStore(conf, StandaloneDB)
} }
// StandaloneDB get a standalone db instance // StandaloneDB get a standalone db instance

Loading…
Cancel
Save