Przeglądaj źródła

Release v0.1.1219

qdy 2 miesięcy temu
commit
eb8c27e5f9
2 zmienionych plików z 57 dodań i 1 usunięć
  1. 56
    0
      db_bootstraps/db_bootstrapper.go
  2. 1
    1
      factory/database/db_factory.go

+ 56
- 0
db_bootstraps/db_bootstrapper.go Wyświetl plik

@@ -0,0 +1,56 @@
1
+package dbbootstraps
2
+
3
+import (
4
+	"log"
5
+
6
+	"git.x2erp.com/qdy/go-base/config"
7
+	"git.x2erp.com/qdy/go-db/factory/database"
8
+)
9
+
10
+// DBBootstrapper 数据库启动器
11
+type DBBootstrapper struct {
12
+	DBFactory *database.DBFactory
13
+	cfg       config.IConfig
14
+}
15
+
16
+// NewDBBootstrapper 创建数据库启动器
17
+func NewDBBootstrapper(cfg config.IConfig) *DBBootstrapper {
18
+	return &DBBootstrapper{
19
+		cfg: cfg,
20
+	}
21
+}
22
+
23
+// Init 初始化数据库
24
+func (db *DBBootstrapper) Init() *DBBootstrapper {
25
+	if db.cfg == nil {
26
+		log.Fatal("配置未初始化,请先传入配置")
27
+	}
28
+
29
+	dbCfg := db.cfg.GetDatabase()
30
+
31
+	log.Printf("正在连接数据库: %s:%d/%s",
32
+		dbCfg.Host, dbCfg.Port, dbCfg.Database)
33
+
34
+	dbFactory, err := database.GetDBFactory()
35
+	if err != nil {
36
+		log.Fatalf("数据库连接失败: %v", err)
37
+	}
38
+
39
+	db.DBFactory = dbFactory
40
+	log.Println("数据库连接成功")
41
+
42
+	return db
43
+}
44
+
45
+// Close 关闭数据库连接
46
+func (db *DBBootstrapper) Close() {
47
+	if db.DBFactory != nil {
48
+		db.DBFactory.Close()
49
+		log.Println("数据库连接已关闭")
50
+	}
51
+}
52
+
53
+// GetDBFactory 获取数据库工厂
54
+func (db *DBBootstrapper) GetDBFactory() *database.DBFactory {
55
+	return db.DBFactory
56
+}

+ 1
- 1
factory/database/db_factory.go Wyświetl plik

@@ -98,7 +98,7 @@ func GetDBFactory() (*DBFactory, error) {
98 98
 }
99 99
 
100 100
 // GetDB 获取数据库连接(线程安全)
101
-func (f *DBFactory) GetDB() *sqlx.DB {
101
+func (f *DBFactory) GetDB() interface{} {
102 102
 	return f.db
103 103
 }
104 104
 

Ładowanie…
Anuluj
Zapisz