소스 검색

支持多微服务和多数据库测试通过

qdy 2 달 전
부모
커밋
0de9889886
2개의 변경된 파일192개의 추가작업 그리고 38개의 파일을 삭제
  1. 189
    37
      main.go
  2. 3
    1
      tables/dim_store.go

+ 189
- 37
main.go 파일 보기

@@ -3,69 +3,221 @@ package main
3 3
 import (
4 4
 	"log"
5 5
 
6
-	"git.x2erp.com/qdy/go-base/bootstraps"
6
+	"git.x2erp.com/qdy/go-db/dbstart"
7 7
 	"git.x2erp.com/qdy/go-db/factory/database"
8
-	"git.x2erp.com/qdy/go-db/sqldef"
9
-	"go-micro.dev/v4/web"
10 8
 
11
-	_ "git.x2erp.com/qdy/go-svc-mercury/tables" // 导入表定义包,触发 init() 函数
9
+	"git.x2erp.com/qdy/go-base/bootstraps"
10
+	"git.x2erp.com/qdy/go-base/ctx"
11
+	"git.x2erp.com/qdy/go-base/logger"
12
+	"git.x2erp.com/qdy/go-base/middleware"
13
+	"git.x2erp.com/qdy/go-base/webx"
12 14
 )
13 15
 
14 16
 var (
15
-	serviceName    = "svc-configure"
17
+	serviceName    = "svc-ai"
16 18
 	serviceVersion = "1"
17 19
 )
18 20
 
21
+// 定义结构体
22
+type CreateUserRequest struct {
23
+	Name  string `json:"name"`
24
+	Email string `json:"email"`
25
+	Age   int    `json:"age"`
26
+}
27
+
28
+type UserResponse struct {
29
+	ID    string `json:"id"`
30
+	Name  string `json:"name"`
31
+	Email string `json:"email"`
32
+	Data  []map[string]interface{}
33
+}
34
+
19 35
 func main() {
36
+	// 1. 初始化基础启动器
37
+	boot := bootstraps.NewBootstrapper(serviceName, serviceVersion)
20 38
 
21
-	// 创建服务启动器
22
-	bootstrapper := bootstraps.NewServiceBootstrapper(serviceName, serviceVersion)
39
+	// 2. 初始化数据库(都在bootstraps包中)
40
+	dbBoot := dbstart.NewDBBootstrapper(boot.GetConfig())
41
+	dbBoot.Init()
23 42
 
24
-	//加载配置
25
-	bootstrapper.InitConfig()
43
+	agentDB := dbBoot.GetDBFactory("agent")
44
+	// 赋值认证中间件参数
45
+	middleware.JWTAuthMiddlewareInit(boot.GetConfig())
26 46
 
27
-	//构建数据库工厂
28
-	bootstrapper.InitDatabase()
47
+	// 3. 启动服务
48
+	//boot.StartService("default")
29 49
 
30
-	//创建表到数据库
31
-	creteTabel(bootstrapper.DbFactory)
50
+	router := boot.GetRouter("default")
51
+	// 3. 创建 WebService 并传入数据库接口
52
+	ws := webx.NewWebService(router)
32 53
 
33
-	// 启动服务,传入路由注册函数
34
-	bootstrapper.Run(registerRoutes)
54
+	//使用默认数据库
55
+	registerDefaultRouter(ws, dbBoot.GetDefaultDBFactory())
35 56
 
57
+	//启动第2个服务
58
+	routerDoris := boot.GetRouter("doris")
59
+	wsDoris := webx.NewWebService(routerDoris)
60
+	registerDorisRouter(wsDoris, agentDB)
61
+
62
+	// 6. 运行服务
63
+	boot.Run(dbBoot)
36 64
 }
37 65
 
38
-// 注册所有路由
39
-func registerRoutes(webService web.Service, dbFactory *database.DBFactory) {
66
+func registerDorisRouter(ws *webx.WebService, dbFactory *database.DBFactory) {
67
+	// GET示例:路径参数绑定
68
+	ws.GET("/app/users/{id}",
69
+		func(id string, reqCtx *ctx.RequestContext) (UserResponse, error) {
70
+
71
+			log.Print("ctx TenantID:", reqCtx.TenantID)
72
+			// id 自动从路径绑定
73
+			// 注意:webx版本没有自动注入dbFactory
74
+			return getUserOracle(id, dbFactory) // 需要修改getUser函数以获取dbFactory
75
+		},
76
+	).Use(middleware.JWTAuthMiddleware).Register()
77
+
78
+	// POST示例:Body参数绑定
79
+	ws.POST("/app/users",
80
+		func(req CreateUserRequest, reqCtx *ctx.RequestContext) (UserResponse, error) {
81
+			log.Print("ctx TenantID:", reqCtx.TenantID)
82
+			// req 自动从JSON Body绑定
83
+			return createUser(req, nil) // 需要修改createUser函数以获取dbFactory
84
+		},
85
+	).Use(middleware.JWTAuthMiddleware).Register()
86
+
87
+	// 您的业务路由
88
+	ws.POST("/app/query/yaml",
89
+		func() (interface{}, error) {
90
+			return queryYaml(nil) // 需要修改queryYaml函数以获取dbFactory
91
+		},
92
+	).Use(middleware.JWTAuthMiddleware).Register()
93
+
94
+	ws.POST("/app/init/config/template",
95
+		func() (interface{}, error) {
96
+			return initConfigTemplate(nil) // 需要修改initConfigTemplate函数以获取dbFactory
97
+		},
98
+	).Use(middleware.JWTAuthMiddleware).Register()
40 99
 
41
-	// // 查询yaml配置文件
42
-	// webService.Handle("/api/query/yaml", middleware.JWTAuthMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
43
-	// 	myhandle.QueryHandlerMap(w, r, dbFactory, service.QueryYamlConfigure)
44
-	// })))
100
+}
45 101
 
46
-	// // 初始化配置模版
47
-	// webService.Handle("/api/init/config/template", middleware.JWTAuthMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
48
-	// 	myhandle.QueryHandlerMap(w, r, dbFactory, service.InitConfigTemplates)
49
-	// })))
102
+func registerDefaultRouter(ws *webx.WebService, dbFactory *database.DBFactory) {
103
+	// GET示例:路径参数绑定
104
+	ws.GET("/api/users/{id}",
105
+		func(id string, reqCtx *ctx.RequestContext) (UserResponse, error) {
106
+
107
+			log.Print("ctx TenantID:", reqCtx.TenantID)
108
+			// id 自动从路径绑定
109
+			// 注意:webx版本没有自动注入dbFactory
110
+			return getUser(id, dbFactory) // 需要修改getUser函数以获取dbFactory
111
+		},
112
+	).Use(middleware.JWTAuthMiddleware).Register()
113
+
114
+	// POST示例:Body参数绑定
115
+	ws.POST("/api/users",
116
+		func(req CreateUserRequest, reqCtx *ctx.RequestContext) (UserResponse, error) {
117
+			log.Print("ctx TenantID:", reqCtx.TenantID)
118
+			// req 自动从JSON Body绑定
119
+			return createUser(req, nil) // 需要修改createUser函数以获取dbFactory
120
+		},
121
+	).Use(middleware.JWTAuthMiddleware).Register()
122
+
123
+	// 您的业务路由
124
+	ws.POST("/api/query/yaml",
125
+		func() (interface{}, error) {
126
+			return queryYaml(nil) // 需要修改queryYaml函数以获取dbFactory
127
+		},
128
+	).Use(middleware.JWTAuthMiddleware).Register()
129
+
130
+	ws.POST("/api/init/config/template",
131
+		func() (interface{}, error) {
132
+			return initConfigTemplate(nil) // 需要修改initConfigTemplate函数以获取dbFactory
133
+		},
134
+	).Use(middleware.JWTAuthMiddleware).Register()
50 135
 
51 136
 }
52 137
 
53
-func creteTabel(factory *database.DBFactory) {
138
+// 4. 创建路由器
139
+// 首先需要创建标准库的ServeMux
140
+//mux := http.NewServeMux()
141
+//router := webx.NewRouter(boot.GetRouter())
142
+//router := webx.NewWebService(mux)
143
+
144
+// 5. 注册路由(Spring风格!)
54 145
 
55
-	// 获取数据库连接和类型
56
-	db := factory.GetDB()
57
-	dbType := factory.GetDBType()
146
+func getUser(id string, dbFactory *database.DBFactory) (UserResponse, error) {
147
+	if dbFactory != nil {
148
+		dbFactory.TestConnection(dbFactory.GetDBType())
149
+	}
150
+
151
+	// 查询数据库...
152
+	return UserResponse{
153
+		ID:    id,
154
+		Name:  "掌扇过去-AAAAA",
155
+		Email: "zhangsan@example.com",
156
+	}, nil
157
+}
58 158
 
59
-	// 创建表同步器
60
-	syncer, err := sqldef.NewTableSyncer(db, dbType)
61
-	if err != nil {
62
-		log.Printf("创建 - 建立器失败: %v", err)
159
+// 业务函数示例
160
+func getUserOracle(id string, dbFactory *database.DBFactory) (UserResponse, error) {
161
+	if dbFactory != nil {
162
+		dbFactory.TestConnection(dbFactory.GetDBType())
63 163
 	}
64 164
 
65
-	// 创建表
66
-	if err := syncer.CreateTables(); err != nil {
67
-		log.Printf("建表失败: %v", err)
165
+	sql, queryParams := getSQLWithPaginationSQL(0, 10)
166
+
167
+	jsonData := dbFactory.QueryPositionalToJSON(sql, queryParams, nil)
168
+	// 查询数据库...
169
+	return UserResponse{
170
+		ID:    id,
171
+		Name:  "掌扇过去",
172
+		Email: "zhangsan@example.com",
173
+		Data:  jsonData.Data,
174
+	}, nil
175
+}
176
+
177
+func createUser(req CreateUserRequest, dbFactory *database.DBFactory) (UserResponse, error) {
178
+	logger.Debug("CreateUserRequest:%v", req)
179
+	return UserResponse{
180
+		ID:    "1",
181
+		Name:  req.Name,
182
+		Email: req.Email,
183
+	}, nil
184
+}
185
+
186
+func queryYaml(dbFactory *database.DBFactory) (interface{}, error) {
187
+	// 您的业务逻辑
188
+	return map[string]interface{}{"message": "query yaml success"}, nil
189
+}
190
+
191
+func initConfigTemplate(dbFactory *database.DBFactory) (interface{}, error) {
192
+	// 您的业务逻辑
193
+	return map[string]interface{}{"message": "init config success"}, nil
194
+}
195
+
196
+// getSQLWithPagination 生成带分页的SQL语句(参数模式)
197
+// 返回SQL语句和参数映射
198
+func getSQLWithPaginationSQL(startRow, endRow int) (string, []interface{}) {
199
+	sql := `SELECT
200
+    CLOTHING_ID,
201
+    CLOTHING_YEAR,
202
+    CLOTHING_NAME
203
+
204
+   FROM (
205
+    SELECT a.*, ROWNUM as rn
206
+    FROM (
207
+        SELECT *
208
+        FROM X6_STOCK_DEV.A3_CLOTHING 
209
+     
210
+        ORDER BY CLOTHING_ID
211
+    ) a
212
+    WHERE ROWNUM <= :1
213
+)
214
+WHERE rn > :2`
215
+
216
+	// 创建参数映射
217
+	params := []interface{}{
218
+		endRow,
219
+		startRow - 1, // WHERE rn > :start_row 所以是startRow-1
68 220
 	}
69 221
 
70
-	log.Println("数据库表建立完成!")
222
+	return sql, params
71 223
 }

+ 3
- 1
tables/dim_store.go 파일 보기

@@ -15,7 +15,8 @@ func init() {
15 15
 			String("store_group_id", 32).Comment("所属店铺组ID").End().
16 16
 			String("region_code", 32).Comment("区域编码").End().
17 17
 			String("creator", 32).NotNull().Comment("创建人").End().
18
-			DateTime("created_at").NotNull().Default("CURRENT_TIMESTAMP").Comment("创建时间").End()
18
+			DateTime("created_at").NotNull().Default("CURRENT_TIMESTAMP").Comment("创建时间").End().
19
+			DateTime("updated_at").NotNull().Default("CURRENT_TIMESTAMP").Comment("最后修改时间").End()
19 20
 		r.RegisterTable(tb.Build())
20 21
 	})
21 22
 }
@@ -28,6 +29,7 @@ type DimStore struct {
28 29
 	RegionCode   string    `gorm:"column:region_code;type:varchar(32);comment:区域编码"`
29 30
 	Creator      string    `gorm:"column:creator;type:varchar(32);not null;comment:创建人"`
30 31
 	CreatedAt    time.Time `gorm:"column:created_at;not null;default:CURRENT_TIMESTAMP;comment:创建时间"`
32
+	UpdatedAt    time.Time `gorm:"column:updated_at;not null;default:CURRENT_TIMESTAMP;comment:最后修改时间"`
31 33
 	TenantId     string    `gorm:"column:tenant_id;type:varchar(8);comment:租户ID"`
32 34
 }
33 35
 

Loading…
취소
저장