github.com/aaabigfish/gopkg@v1.1.0/database/orm/orm.go (about)

     1  package orm
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  
     7  	"golang.org/x/sync/singleflight"
     8  	"gorm.io/driver/mysql"
     9  	"gorm.io/gorm"
    10  
    11  	"github.com/aaabigfish/gopkg/config"
    12  )
    13  
    14  var (
    15  	sfg singleflight.Group
    16  	rwl sync.RWMutex
    17  
    18  	dbs = map[string]*DB{}
    19  )
    20  
    21  // DB 扩展 sqlx.DB
    22  type DB struct {
    23  	*gorm.DB
    24  }
    25  
    26  // Get 获取数据库实例
    27  // db := mysql.Get("foo")
    28  func Get(name string, conf ...*gorm.Config) *DB {
    29  	rwl.RLock()
    30  	if db, ok := dbs[name]; ok {
    31  		rwl.RUnlock()
    32  		return db
    33  	}
    34  	rwl.RUnlock()
    35  
    36  	v, _, _ := sfg.Do(name, func() (interface{}, error) {
    37  		dbConf := config.NewDbConfig(name)
    38  		if len(dbConf.Type) == 0 {
    39  			dbConf.Type = "mysql"
    40  		}
    41  
    42  		c := &gorm.Config{}
    43  		if len(conf) > 0 {
    44  			c = conf[0]
    45  		}
    46  
    47  		db, err := gorm.Open(mysql.Open(dbConf.Dsn), c)
    48  		if err != nil {
    49  			panic(err.Error())
    50  		}
    51  
    52  		if config.DbMode == "debug" {
    53  			db = db.Debug()
    54  		}
    55  
    56  		sdb, err := db.DB()
    57  		if err != nil {
    58  			panic(err.Error())
    59  		}
    60  		sdb.SetMaxIdleConns(dbConf.MaxIdle)
    61  		sdb.SetMaxOpenConns(dbConf.MaxActive)
    62  		sdb.SetConnMaxLifetime(time.Duration(dbConf.IdleTimeout) * time.Second)
    63  
    64  		newDB := &DB{db}
    65  
    66  		rwl.Lock()
    67  		defer rwl.Unlock()
    68  		dbs[name] = newDB
    69  
    70  		return newDB, nil
    71  	})
    72  
    73  	return v.(*DB)
    74  }