go_dreamfactory/modules/dbmodel.go
2022-06-15 14:09:41 +08:00

80 lines
1.6 KiB
Go

package modules
import (
"fmt"
"go_dreamfactory/lego/sys/log"
"go_dreamfactory/lego/sys/redis"
"go_dreamfactory/sys/cache"
"go.mongodb.org/mongo-driver/bson"
"google.golang.org/protobuf/proto"
)
type Action string
const (
INSERT Action = "insert"
UPDATE Action = "update"
DELETE Action = "delete"
)
type DBModel struct {
*MComp_DBComp
pbData proto.Message
prefix string //rediskey前缀
tableName string
}
func NewDBModel(c *MComp_DBComp) *DBModel {
return &DBModel{MComp_DBComp: c}
}
func (m *DBModel) SetData(model proto.Message) *DBModel {
m.pbData = model
return m
}
func (m *DBModel) GetData() proto.Message {
return m.pbData
}
func (m *DBModel) SetPrefix(prefix string) {
m.prefix = prefix
}
func (m *DBModel) SetTableName(tableName string) {
m.tableName = tableName
}
func (m *DBModel) OnChange(key string) {
m.MComp_DBComp.InsertModelLogs(m.tableName, key, m.pbData)
}
func (m *DBModel) Set(key string, act Action) {
//调用写入mongo日志接口
switch act {
case INSERT:
m.MComp_DBComp.InsertModelLogs(m.tableName, key, m.pbData)
case UPDATE:
m.MComp_DBComp.UpdateModelLogs(m.tableName, key, bson.M{"_id": key}, m.pbData)
case DELETE:
m.MComp_DBComp.DeleteModelLogs(m.tableName, key, bson.M{"_id": key})
}
}
//获取数据
func (m *DBModel) Get(uid string) {
if m.prefix == "" {
log.Errorf("get data err,because prefix not setting")
return
}
err := cache.Redis().Get(fmt.Sprintf("%s:%s", m.prefix, uid), m.pbData)
if err != nil {
if err.Error() != redis.RedisNil.Error() {
log.Errorf("err:%v", err)
}
return
}
}