package db import ( "fmt" "gim/internal/business/comm/db/model" "gim/internal/business/comm/md" "gim/internal/business/comm/utils" "gim/internal/business/comm/utils/logx" "gim/pkg/db" "gim/pkg/gerrors" ) type dbSysCfg struct{} var DbSysCfg = new(dbSysCfg) // SysCfgGetAll 获取系统配置 func (*dbSysCfg) SysCfgGetAll(masterId int64) (*[]model.SysCfg, error) { var cfgList []model.SysCfg if err := db.DB.Where("`master_id`=?", masterId).Find(&cfgList).Error; err != nil { return nil, gerrors.WrapError(err) } return &cfgList, nil } // SysCfgGetOne 获取一条记录 func (*dbSysCfg) SysCfgGetOne(key string, masterId int64) (*model.SysCfg, error) { var cfgList model.SysCfg if err := db.DB.Where("`key` = ? and `master_id` = ?", key, masterId).First(&cfgList).Error; err != nil { return nil, gerrors.WrapError(err) } return &cfgList, nil } // SysCfgInsert 插入一条配置信息 func (*dbSysCfg) SysCfgInsert(key, val, memo string, masterId int64) bool { cfg := model.SysCfg{Key: key, Val: val, Memo: memo, MasterId: masterId} err := db.DB.Create(&cfg).Error if err != nil { logx.Error(err) return false } return true } // SysCfgUpdate 修改某条配置信息 func (*dbSysCfg) SysCfgUpdate(key, val, memo string, masterId int64) bool { cfg := model.SysCfg{Key: key, Val: val, Memo: memo} err := db.DB.Where("`key` = ? and `master_id` = ?", key, masterId).Update(&cfg).Error if err != nil { logx.Error(err) return false } return true } // SysCfgGetWithDb 单条记录获取 func (*dbSysCfg) SysCfgGetWithDb(masterId string, HKey string) string { cacheKey := fmt.Sprintf(md.AppCfgCacheKey, masterId, HKey[0:1]) get, err := db.RedisUtil.HGetString(cacheKey, HKey) if err != nil || get == "" { cfg, err := DbSysCfg.SysCfgGetOne(HKey, utils.StrToInt64(masterId)) if err != nil || cfg == nil { _ = logx.Error(err) return "" } // key是否存在 cacheKeyExist := false if db.RedisUtil.Exists(cacheKey) { cacheKeyExist = true } // 设置缓存 _, err = db.RedisUtil.HSet(cacheKey, HKey, cfg.Val) if err != nil { _ = logx.Error(err) return "" } if !cacheKeyExist { // 如果是首次设置 设置过期时间 _, err := db.RedisUtil.Expire(cacheKey, md.CfgCacheTime) if err != nil { _ = logx.Error(err) return "" } } return cfg.Val } return get } // SysCfgFindWithDb 多条记录获取 func (*dbSysCfg) SysCfgFindWithDb(masterId string, keys ...string) map[string]string { res := map[string]string{} cacheKey := fmt.Sprintf(md.AppCfgCacheKey, masterId) err := db.RedisUtil.GetJson(cacheKey, &res) if err != nil || len(res) == 0 { cfgList, _ := DbSysCfg.SysCfgGetAll(utils.StrToInt64(masterId)) if cfgList == nil { return nil } for _, v := range *cfgList { res[v.Key] = v.Val } db.RedisUtil.SetJson(cacheKey, res, md.CfgCacheTime) } if len(keys) == 0 { return res } tmp := map[string]string{} for _, v := range keys { if val, ok := res[v]; ok { tmp[v] = val } else { tmp[v] = "" } } return tmp }