package db import ( "applet/app/db/model" "applet/app/md" "applet/app/utils/cache" "applet/app/utils/logx" ) func CountyGetAll() (*[]model.County, error) { var CountyList []model.County if err := Db.Cols("id,name").Find(&CountyList); err != nil { return nil, logx.Error(err) } return &CountyList, nil } // 获取一条记录 func CountyGetOne(key string) (*model.County, error) { var County model.County if has, err := Db.Where("`id`=?", key).Get(&County); err != nil || has == false { if has == false { return &County, nil } return nil, logx.Error(err) } return &County, nil } //单条记录获取DB func CountyGetWithDb(HKey string) string { cacheKey := md.OfficialCountyCacheKey get, err := cache.HGetString(cacheKey, HKey) if err != nil || get == "" { County, err := CountyGetOne(HKey) if err != nil || County == nil { _ = logx.Error(err) return "" } // key是否存在 cacheKeyExist := false if cache.Exists(cacheKey) { cacheKeyExist = true } // 设置缓存 _, err = cache.HSet(cacheKey, HKey, County.Name) if err != nil { _ = logx.Error(err) return "" } if !cacheKeyExist { // 如果是首次设置 设置过期时间 _, err := cache.Expire(cacheKey, md.CfgCacheTime) if err != nil { _ = logx.Error(err) return "" } } return County.Name } return get } func CountyFindWithDb(keys ...string) map[string]string { res := map[string]string{} cacheKey := md.OfficialCountyCacheKey err := cache.GetJson(cacheKey, &res) if err != nil || len(res) == 0 { CountyList, _ := CountyGetAll() if CountyList == nil { return nil } for _, v := range *CountyList { res[v.Id] = v.Name } cache.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 }