|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- package db
-
- import (
- "egg-im/internal/business/comm/db/model"
- "egg-im/internal/business/comm/md"
- "egg-im/internal/business/comm/utils/logx"
- "egg-im/pkg/db"
- "egg-im/pkg/gerrors"
- "fmt"
- )
-
- type dbSysCfg struct{}
-
- var DbSysCfg = new(dbSysCfg)
-
- // SysCfgGetAll 获取系统配置
- func (*dbSysCfg) SysCfgGetAll() (*[]model.SysCfg, error) {
- var cfgList []model.SysCfg
- if err := db.DB.Where("1=1").Find(&cfgList).Error; err != nil {
- return nil, gerrors.WrapError(err)
- }
- return &cfgList, nil
- }
-
- // SysCfgGetOne 获取一条记录
- func (*dbSysCfg) SysCfgGetOne(key string) (*model.SysCfg, error) {
- var cfgList model.SysCfg
- if err := db.DB.Where("`key` = ?", key).First(&cfgList).Error; err != nil {
- return nil, gerrors.WrapError(err)
- }
- return &cfgList, nil
- }
-
- // SysCfgInsert 插入一条配置信息
- func (*dbSysCfg) SysCfgInsert(key, val, memo string) bool {
- cfg := model.SysCfg{Key: key, Val: val, Memo: memo}
- err := db.DB.Create(&cfg).Error
- if err != nil {
- logx.Error(err)
- return false
- }
- return true
- }
-
- // SysCfgUpdate 修改某条配置信息
- func (*dbSysCfg) SysCfgUpdate(key, val, memo string) bool {
- cfg := model.SysCfg{Key: key, Val: val, Memo: memo}
- err := db.DB.Where("`key` = ?", key).Update(&cfg).Error
- if err != nil {
- logx.Error(err)
- return false
- }
- return true
- }
-
- // SysCfgGetWithDb 单条记录获取
- func (*dbSysCfg) SysCfgGetWithDb(HKey string) string {
- cacheKey := fmt.Sprintf(md.AppCfgCacheKey, HKey[0:1])
- get, err := db.RedisUtil.HGetString(cacheKey, HKey)
- if err != nil || get == "" {
- cfg, err := DbSysCfg.SysCfgGetOne(HKey)
- 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(keys ...string) map[string]string {
- res := map[string]string{}
- cacheKey := fmt.Sprintf("egg_im_cfg_cache")
- err := db.RedisUtil.GetJson(cacheKey, &res)
- if err != nil || len(res) == 0 {
- cfgList, _ := DbSysCfg.SysCfgGetAll()
- 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
- }
|