Commit 8ec7d2615de12ed2ef9c51de1104269c82dcc20c

Authored by 王家文
1 parent d5604573
Exists in master and in 1 other branch dev-wjw

refactor♻️:redis对象和mysql对象持久化和读取

configs/registry.go
... ... @@ -3,6 +3,7 @@ package configs
3 3 import (
4 4 "apigame/service-common/svmysql"
5 5 "apigame/service-common/svredis"
  6 + "apigame/util/util-lx/lxalilog"
6 7 "fmt"
7 8 )
8 9  
... ... @@ -16,6 +17,7 @@ func GetApiGameConfig(gameId string) (conf *ApiGameConfig, err error) {
16 17 }
17 18 has, err = svmysql.First(conf, gameId)
18 19 if err != nil {
  20 + lxalilog.Errors(err, "configs.GetApiGameConfig error", gameId)
19 21 return
20 22 }
21 23 if !has {
... ... @@ -39,6 +41,7 @@ func GetCardActivityConfig(gameId string) (conf *CardActivityConfig, has bool) {
39 41 confRaw := new(CardActivityConfigRaw)
40 42 has, err = svmysql.First(confRaw, gameId)
41 43 if err != nil {
  44 + lxalilog.Errors(err, "configs.GetCardActivityConfig error", gameId)
42 45 return
43 46 }
44 47 if !has {
... ... @@ -65,9 +68,11 @@ func GetRoomRankConfig(gameId string) (conf *RoomRankConfig, has bool) {
65 68 confRaw := new(RoomRankConfigRaw)
66 69 has, err = svmysql.First(confRaw, gameId)
67 70 if err != nil {
  71 + lxalilog.Errors(err, "configs.GetRoomRankConfig error", gameId)
68 72 return
69 73 }
70 74 if !has {
  75 +
71 76 return
72 77 }
73 78  
... ...
service-common/svconst/mysql.go
... ... @@ -19,5 +19,5 @@ const (
19 19  
20 20 MYSQL_TABLE_S_ROOMRANK_CONFIG = "s_roomrank_activity_" // 房间排行活动配置
21 21 MYSQL_TABLE_S_ROOMRANK_PLAYER = "s_roomrank_player_" // 房间排行玩家数据
22   - MYSQL_TABLE_S_ROOMRANK_ROOM = "s_roomrank_room_" // 房间排行房间数据
  22 + MYSQL_TABLE_S_ROOMRANK_ROOM = "s_roomrank_room" // 房间排行房间数据
23 23 )
... ...
service-common/svmysql/dto.go
1 1 package svmysql
2 2  
3   -import (
4   - "apigame/util/util-lx/lxalilog"
5   - "gorm.io/gorm"
6   - "strings"
7   -)
  3 +func InitTable(obj IMysqlData, suffix string, notify bool) {
  4 + info := obj.MysqlInfo(suffix)
  5 + db := info.DbMysql
  6 + _ = db.Table(info.TableName).AutoMigrate(obj)
  7 +}
8 8  
9   -func Insert(obj IMysqlData, suffix string) (err error) {
  9 +func Create(obj IMysqlData, suffix string) (err error) {
10 10 info := obj.MysqlInfo(suffix)
11 11 db := info.DbMysql
12   - stmt := db.Session(&gorm.Session{DryRun: true}).Create(obj).Statement
13   - stmtSQL := stmt.SQL.String()
14   - sql := strings.Replace(stmtSQL, stmt.Table, info.TableName, -1)
15   - result := db.Exec(sql, stmt.Vars...)
  12 + result := db.Table(info.TableName).Create(obj)
  13 +
16 14 err = result.Error
17 15 if err != nil {
18   - lxalilog.Errors(err, suffix)
19 16 return
20 17 }
21 18 return
... ... @@ -24,13 +21,10 @@ func Insert(obj IMysqlData, suffix string) (err error) {
24 21 func Updates(obj IMysqlData, suffix string) (err error) {
25 22 info := obj.MysqlInfo(suffix)
26 23 db := info.DbMysql
27   - stmt := db.Session(&gorm.Session{DryRun: true}).Updates(obj).Statement
28   - stmtSQL := stmt.SQL.String()
29   - sql := strings.Replace(stmtSQL, stmt.Table, info.TableName, -1)
30   - result := db.Exec(sql, stmt.Vars...)
  24 + result := db.Table(info.TableName).Updates(obj)
  25 +
31 26 err = result.Error
32 27 if err != nil {
33   - lxalilog.Errors(err, suffix)
34 28 return
35 29 }
36 30 return
... ... @@ -39,14 +33,10 @@ func Updates(obj IMysqlData, suffix string) (err error) {
39 33 func Save(obj IMysqlData, suffix string) (err error) {
40 34 info := obj.MysqlInfo(suffix)
41 35 db := info.DbMysql
42   - stmt := db.Session(&gorm.Session{DryRun: true}).Save(obj).Statement
43   - stmtSQL := stmt.SQL.String()
44   - sql := strings.Replace(stmtSQL, stmt.Table, info.TableName, -1)
45   - result := db.Exec(sql, stmt.Vars...)
  36 + result := db.Table(info.TableName).Save(obj)
46 37  
47 38 err = result.Error
48 39 if err != nil {
49   - lxalilog.Errors(err, suffix)
50 40 return
51 41 }
52 42 return
... ... @@ -55,31 +45,19 @@ func Save(obj IMysqlData, suffix string) (err error) {
55 45 func First(obj IMysqlData, suffix string) (has bool, err error) {
56 46 info := obj.MysqlInfo(suffix)
57 47 db := info.DbMysql
58   - stmt := db.Session(&gorm.Session{DryRun: true}).First(obj).Statement
59   - stmtSQL := stmt.SQL.String()
60   - sql := strings.Replace(stmtSQL, stmt.Table, info.TableName, -1)
61   - result := db.Raw(sql, stmt.Vars...).Scan(obj)
  48 + result := db.Table(info.TableName).First(obj)
  49 +
62 50 has = result.RowsAffected != 0
63 51 err = result.Error
64   - if err != nil {
65   - lxalilog.Errors(err, suffix)
66   - return
67   - }
68 52 return
69 53 }
70 54  
71 55 func Find(obj IMysqlData, suffix string) (has bool, err error) {
72 56 info := obj.MysqlInfo(suffix)
73 57 db := info.DbMysql
74   - stmt := db.Session(&gorm.Session{DryRun: true}).Find(obj).Statement
75   - stmtSQL := stmt.SQL.String()
76   - sql := strings.Replace(stmtSQL, stmt.Table, info.TableName, -1)
77   - result := db.Raw(sql, stmt.Vars...).Scan(obj)
  58 + result := db.Table(info.TableName).Find(obj)
  59 +
78 60 has = result.RowsAffected != 0
79 61 err = result.Error
80   - if err != nil {
81   - lxalilog.Errors(err, suffix)
82   - return
83   - }
84 62 return
85 63 }
... ...
service-common/svmysql/index.go
... ... @@ -6,6 +6,10 @@ import (
6 6 "github.com/astaxie/beego"
7 7 "gorm.io/driver/mysql"
8 8 "gorm.io/gorm"
  9 + "gorm.io/gorm/logger"
  10 + "log"
  11 + "os"
  12 + "time"
9 13 )
10 14  
11 15 func Init() bool {
... ... @@ -34,5 +38,17 @@ func Init() bool {
34 38 }
35 39  
36 40 func ConnectMySQL(dsn string) (db *gorm.DB, err error) {
37   - return gorm.Open(mysql.Open(dsn), &gorm.Config{})
  41 + newLogger := logger.New(
  42 + log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
  43 + logger.Config{
  44 + SlowThreshold: time.Second, // Slow SQL threshold
  45 + LogLevel: logger.Silent, // Log level
  46 + IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
  47 + ParameterizedQueries: true, // Don't include params in the SQL log
  48 + Colorful: false, // Disable color
  49 + },
  50 + )
  51 + return gorm.Open(mysql.Open(dsn), &gorm.Config{
  52 + Logger: newLogger,
  53 + })
38 54 }
... ...
service-common/svmysql/table.go
... ... @@ -1,137 +0,0 @@
1   -package svmysql
2   -
3   -import (
4   - "fmt"
5   - "gorm.io/driver/mysql"
6   - "gorm.io/gorm"
7   - "gorm.io/gorm/clause"
8   - "gorm.io/gorm/migrator"
9   - "strings"
10   -)
11   -
12   -func InitTable(obj IMysqlData, suffix string, notify bool) {
13   - info := obj.MysqlInfo(suffix)
14   - db := info.DbMysql
15   - tableName := info.TableName
16   - m := db.Migrator().(mysql.Migrator).Migrator
17   - queryTx, execTx := m.GetQueryAndExecTx()
18   - if HasTable(queryTx.Migrator().(mysql.Migrator).Migrator, obj, tableName) {
19   - if notify {
20   - fmt.Println(tableName + " exist, skip!")
21   - }
22   - } else {
23   - err := CreateTable(execTx, obj, tableName)
24   - if err != nil {
25   - fmt.Println("err", err)
26   - }
27   - }
28   -}
29   -
30   -func HasTable(m migrator.Migrator, obj any, tableName string) bool {
31   - var count int64
32   -
33   - m.RunWithValue(obj, func(stmt *gorm.Statement) error {
34   - currentDatabase := m.DB.Migrator().CurrentDatabase()
35   - return m.DB.Raw("SELECT count(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ? AND table_type = ?", currentDatabase, tableName, "BASE TABLE").Row().Scan(&count)
36   - })
37   -
38   - return count > 0
39   -}
40   -
41   -func CreateTable(execTx *gorm.DB, value any, tableName string) error {
42   - m := execTx.Migrator().(mysql.Migrator).Migrator
43   - tx := m.DB.Session(&gorm.Session{})
44   -
45   - if err := m.RunWithValue(value, func(stmt *gorm.Statement) (err error) {
46   - var (
47   - createTableSQL = "CREATE TABLE ? ("
48   - values = []interface{}{clause.Table{Name: tableName}}
49   - hasPrimaryKeyInDataType bool
50   - )
51   -
52   - for _, dbName := range stmt.Schema.DBNames {
53   - field := stmt.Schema.FieldsByDBName[dbName]
54   - if !field.IgnoreMigration {
55   - createTableSQL += "? ?"
56   - hasPrimaryKeyInDataType = hasPrimaryKeyInDataType || strings.Contains(strings.ToUpper(m.DataTypeOf(field)), "PRIMARY KEY")
57   - values = append(values, clause.Column{Name: dbName}, m.DB.Migrator().FullDataTypeOf(field))
58   - createTableSQL += ","
59   - }
60   - }
61   -
62   - if !hasPrimaryKeyInDataType && len(stmt.Schema.PrimaryFields) > 0 {
63   - createTableSQL += "PRIMARY KEY ?,"
64   - primaryKeys := make([]interface{}, 0, len(stmt.Schema.PrimaryFields))
65   - for _, field := range stmt.Schema.PrimaryFields {
66   - primaryKeys = append(primaryKeys, clause.Column{Name: field.DBName})
67   - }
68   -
69   - values = append(values, primaryKeys)
70   - }
71   -
72   - for _, idx := range stmt.Schema.ParseIndexes() {
73   - if m.CreateIndexAfterCreateTable {
74   - defer func(value interface{}, name string) {
75   - if err == nil {
76   - err = tx.Migrator().CreateIndex(value, name)
77   - }
78   - }(value, idx.Name)
79   - } else {
80   - if idx.Class != "" {
81   - createTableSQL += idx.Class + " "
82   - }
83   - createTableSQL += "INDEX ? ?"
84   -
85   - if idx.Comment != "" {
86   - createTableSQL += fmt.Sprintf(" COMMENT '%s'", idx.Comment)
87   - }
88   -
89   - if idx.Option != "" {
90   - createTableSQL += " " + idx.Option
91   - }
92   -
93   - createTableSQL += ","
94   - values = append(values, clause.Column{Name: idx.Name}, tx.Migrator().(migrator.BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt))
95   - }
96   - }
97   -
98   - if !m.DB.DisableForeignKeyConstraintWhenMigrating && !m.DB.IgnoreRelationshipsWhenMigrating {
99   - for _, rel := range stmt.Schema.Relationships.Relations {
100   - if rel.Field.IgnoreMigration {
101   - continue
102   - }
103   - if constraint := rel.ParseConstraint(); constraint != nil {
104   - if constraint.Schema == stmt.Schema {
105   - sql, vars := constraint.Build()
106   - createTableSQL += sql + ","
107   - values = append(values, vars...)
108   - }
109   - }
110   - }
111   - }
112   -
113   - for _, uni := range stmt.Schema.ParseUniqueConstraints() {
114   - createTableSQL += "CONSTRAINT ? UNIQUE (?),"
115   - values = append(values, clause.Column{Name: uni.Name}, clause.Expr{SQL: stmt.Quote(uni.Field.DBName)})
116   - }
117   -
118   - for _, chk := range stmt.Schema.ParseCheckConstraints() {
119   - createTableSQL += "CONSTRAINT ? CHECK (?),"
120   - values = append(values, clause.Column{Name: chk.Name}, clause.Expr{SQL: chk.Constraint})
121   - }
122   -
123   - createTableSQL = strings.TrimSuffix(createTableSQL, ",")
124   -
125   - createTableSQL += ")"
126   -
127   - if tableOption, ok := m.DB.Get("gorm:table_options"); ok {
128   - createTableSQL += fmt.Sprint(tableOption)
129   - }
130   -
131   - err = tx.Exec(createTableSQL, values...).Error
132   - return err
133   - }); err != nil {
134   - return err
135   - }
136   - return nil
137   -}
service/cardholder/logic.go
... ... @@ -196,7 +196,7 @@ func DoOpen(gameId string,
196 196 // 记录开卡包日志
197 197 {
198 198 recordBase := NewRecordCardHolderBase(player.Uid, sequenceId, cohort, config.Id, player.Details.Round)
199   - _ = svmysql.Insert(NewRecordCardHolderOpen(recordBase,
  199 + _ = svmysql.Create(NewRecordCardHolderOpen(recordBase,
200 200 openMode, utstring.StringToInt(confCardholder.Id), utjson.JsonString(newCards)),
201 201 gameId)
202 202 }
... ... @@ -245,7 +245,7 @@ func DoOpenCheckAward(gameId string,
245 245 {
246 246 // 记录日志
247 247 recordBase := NewRecordCardHolderBase(player.Uid, sequenceId, cohort, config.Id, player.Details.Round)
248   - _ = svmysql.Insert(NewRecordCardHolderRewardAlbum(recordBase,
  248 + _ = svmysql.Create(NewRecordCardHolderRewardAlbum(recordBase,
249 249 albumId, award),
250 250 gameId)
251 251 }
... ... @@ -257,7 +257,7 @@ func DoOpenCheckAward(gameId string,
257 257  
258 258 // 记录日志
259 259 recordBase := NewRecordCardHolderBase(player.Uid, sequenceId, cohort, config.Id, player.Details.Round)
260   - _ = svmysql.Insert(NewRecordCardHolderRewardRound(recordBase,
  260 + _ = svmysql.Create(NewRecordCardHolderRewardRound(recordBase,
261 261 awardRound),
262 262 gameId)
263 263  
... ...
service/cardholder/player.go
... ... @@ -3,6 +3,7 @@ package cardholder
3 3 import (
4 4 "apigame/configs"
5 5 "apigame/service-common/svmysql"
  6 + "apigame/util/util-lx/lxalilog"
6 7 "apigame/util/util-lx/lxtime"
7 8 )
8 9  
... ... @@ -11,20 +12,24 @@ func SavePlayer(gameId string, d *DataCardHolder) {
11 12 d.UpdateTime = lxtime.NowUninx()
12 13 d.Encode()
13 14  
14   - _ = svmysql.Save(d, gameId)
  15 + err := svmysql.Save(d, gameId)
  16 + if err != nil {
  17 + lxalilog.Errors(err, "cardholder.SavePlayer error", gameId, d.Uid, d.ActivityId)
  18 + }
15 19 }
16 20  
17 21 func _LoadPlayer(gameId string, uid int64) (d *DataCardHolder) {
18 22 d = NewDataCardHolder(uid)
19 23 has, err := svmysql.First(d, gameId)
20   - if err != nil {
21   - return
22   - }
23 24 if has {
24 25 d.Decode()
25 26 } else {
26 27 d.Init(uid)
27   - _ = svmysql.Insert(d, gameId)
  28 + err = svmysql.Create(d, gameId)
  29 + if err != nil {
  30 + lxalilog.Errors(err, "cardholder._LoadPlayer Create error", gameId, d.Uid, d.ActivityId)
  31 + return
  32 + }
28 33 }
29 34 return
30 35 }
... ...
service/roomrank/dto-room.go
... ... @@ -20,10 +20,6 @@ func (d *DataRoomRankRoom) MysqlInfo(suffix string) *svmysql.MysqlInfo {
20 20 tableName := svconst.MYSQL_TABLE_S_ROOMRANK_ROOM
21 21 return &svmysql.MysqlInfo{
22 22 DbMysql: svconst.DbCommon,
23   - TableName: tableName + suffix,
  23 + TableName: fmt.Sprintf("%s_%s_%d", tableName, suffix, d.ActivityId),
24 24 }
25 25 }
26   -
27   -func (d *DataRoomRankRoom) GetSuffix(gameId string) string {
28   - return fmt.Sprintf("%s_%d", gameId, d.ActivityId)
29   -}
... ...
service/roomrank/player.go
... ... @@ -4,6 +4,7 @@ import (
4 4 "apigame/configs"
5 5 "apigame/models"
6 6 "apigame/service-common/svmysql"
  7 + "apigame/util/util-lx/lxalilog"
7 8 "apigame/util/util-lx/lxtime"
8 9 )
9 10  
... ... @@ -11,19 +12,24 @@ import (
11 12 func SavePlayer(gameId string, d *DataRoomRankPlayer) {
12 13 d.UpdateTime = lxtime.NowUninx()
13 14  
14   - _ = svmysql.Save(d, gameId)
  15 + err := svmysql.Save(d, gameId)
  16 + if err != nil {
  17 + lxalilog.Errors(err, "roomrank.SavePlayer error", gameId, d.Uid, d.ActivityId)
  18 + return
  19 + }
15 20 }
16 21  
17 22 func _LoadPlayer(gameId string, uid int64) (d *DataRoomRankPlayer) {
18 23 d = NewDataRoomRankPlayer(uid)
19 24 has, err := svmysql.First(d, gameId)
20   - if err != nil {
21   - return
22   - }
23 25 if has {
24 26 } else {
25 27 d.Init(uid)
26   - _ = svmysql.Insert(d, gameId)
  28 + err = svmysql.Create(d, gameId)
  29 + if err != nil {
  30 + lxalilog.Errors(err, "roomrank._LoadPlayer Create error", gameId, d.Uid, d.ActivityId)
  31 + return
  32 + }
27 33 }
28 34 return
29 35 }
... ...
service/roomrank/room.go
... ... @@ -7,8 +7,7 @@ import (
7 7 )
8 8  
9 9 func tryInitTable(gameId string, d *DataRoomRankRoom) {
10   - suffix := d.GetSuffix(gameId)
11   - svmysql.InitTable(d, suffix, false)
  10 + svmysql.InitTable(d, gameId, false)
12 11 }
13 12  
14 13 // SaveRoom 存储数据
... ... @@ -17,21 +16,24 @@ func SaveRoom(gameId string, d *DataRoomRankRoom) {
17 16  
18 17 d.UpdateTime = lxtime.NowUninx()
19 18  
20   - suffix := d.GetSuffix(gameId)
21   - _ = svmysql.Save(d, suffix)
  19 + err := svmysql.Save(d, gameId)
  20 + if err != nil {
  21 + lxalilog.Errors(err, "roomrank.SaveRoom error", gameId, d.Uid, d.ActivityId)
  22 + return
  23 + }
22 24 }
23 25  
24 26 // LoadRoom 获取数据 外部接口
25   -func LoadRoom(gameId string, id int64, activityId int64) (d *DataRoomRankRoom) {
  27 +func LoadRoom(gameId string, id int64, activityId int64) (d *DataRoomRankRoom, has bool) {
26 28 d = &DataRoomRankRoom{Id: id, ActivityId: activityId}
27 29 tryInitTable(gameId, d)
28   - suffix := d.GetSuffix(gameId)
29   - has, err := svmysql.First(d, suffix)
  30 +
  31 + var err error
  32 + has, err = svmysql.First(d, gameId)
30 33 if err != nil {
31   - return
32   - }
33   - if !has {
34 34 lxalilog.Errors(err, "roomrank.LoadRoom error", gameId, id, activityId)
  35 + return
35 36 }
  37 +
36 38 return
37 39 }
... ...