github.com/OrigamiWang/msd/micro@v0.0.0-20240229032328-b62246268db9/model/dao/db.go (about)

     1  package dao
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/OrigamiWang/msd/micro/confparser"
     7  	"github.com/OrigamiWang/msd/micro/const/db"
     8  	logutil "github.com/OrigamiWang/msd/micro/util/log"
     9  	"github.com/redis/go-redis/v9"
    10  	"gorm.io/gorm"
    11  )
    12  
    13  // 初始化databases
    14  var dbConns = make(map[string]interface{}, 0)
    15  
    16  func init() {
    17  	InitDb()
    18  }
    19  func InitDb() {
    20  	fmt.Println("init db...")
    21  	if confparser.Conf == nil {
    22  		return
    23  	}
    24  	dbs := confparser.Conf.Dbs
    25  	if dbs == nil {
    26  		logutil.Warn("dbs is nil")
    27  		return
    28  	}
    29  	for _, _db := range dbs {
    30  		switch _db.Type {
    31  		case db.MYSQL:
    32  			conn := InitMysql(&_db)
    33  			if conn == nil {
    34  				continue
    35  			}
    36  			dbConns[_db.Key] = conn
    37  		case db.REDIS:
    38  			conn := InitRedis(&_db)
    39  			if conn == nil {
    40  				continue
    41  			}
    42  			dbConns[_db.Key] = conn
    43  		case db.MONGODB:
    44  			continue
    45  		default:
    46  			continue
    47  		}
    48  	}
    49  }
    50  
    51  func DelDB() {
    52  	dbConns = make(map[string]interface{}, 0)
    53  }
    54  
    55  // MySQL 返回mysql数据库
    56  func MySQL(key string) (*gorm.DB, error) {
    57  	fmt.Println("mysql...")
    58  	if v, ok := dbConns[key]; ok {
    59  		return v.(*gorm.DB), nil
    60  	}
    61  	logutil.Error("get mysql failed, err")
    62  	return nil, fmt.Errorf("get mysql failed, err")
    63  }
    64  
    65  func Redis(key string) (*redis.Client, error) {
    66  	fmt.Println("redis...")
    67  	if v, ok := dbConns[key]; ok {
    68  		return v.(*redis.Client), nil
    69  	}
    70  	logutil.Error("get redis failed")
    71  	return nil, fmt.Errorf("get redis failed")
    72  }