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