golang 的 rabbitmq 消费项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db_city.go 1.8 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package db
  2. import (
  3. "applet/app/db/model"
  4. "applet/app/md"
  5. "applet/app/utils/cache"
  6. "applet/app/utils/logx"
  7. )
  8. func CityGetAll() (*[]model.City, error) {
  9. var CityList []model.City
  10. if err := Db.Cols("id,name").Find(&CityList); err != nil {
  11. return nil, logx.Error(err)
  12. }
  13. return &CityList, nil
  14. }
  15. // 获取一条记录
  16. func CityGetOne(key string) (*model.City, error) {
  17. var City model.City
  18. if has, err := Db.Where("`id`=?", key).Get(&City); err != nil || has == false {
  19. if has == false {
  20. return &City, nil
  21. }
  22. return nil, logx.Error(err)
  23. }
  24. return &City, nil
  25. }
  26. //单条记录获取DB
  27. func CityGetWithDb(HKey string) string {
  28. cacheKey := md.OfficialCityCacheKey
  29. get, err := cache.HGetString(cacheKey, HKey)
  30. if err != nil || get == "" {
  31. City, err := CityGetOne(HKey)
  32. if err != nil || City == nil {
  33. _ = logx.Error(err)
  34. return ""
  35. }
  36. // key是否存在
  37. cacheKeyExist := false
  38. if cache.Exists(cacheKey) {
  39. cacheKeyExist = true
  40. }
  41. // 设置缓存
  42. _, err = cache.HSet(cacheKey, HKey, City.Name)
  43. if err != nil {
  44. _ = logx.Error(err)
  45. return ""
  46. }
  47. if !cacheKeyExist { // 如果是首次设置 设置过期时间
  48. _, err := cache.Expire(cacheKey, md.CfgCacheTime)
  49. if err != nil {
  50. _ = logx.Error(err)
  51. return ""
  52. }
  53. }
  54. return City.Name
  55. }
  56. return get
  57. }
  58. func CityFindWithDb(keys ...string) map[string]string {
  59. res := map[string]string{}
  60. cacheKey := md.OfficialCityCacheKey
  61. err := cache.GetJson(cacheKey, &res)
  62. if err != nil || len(res) == 0 {
  63. CityList, _ := CityGetAll()
  64. if CityList == nil {
  65. return nil
  66. }
  67. for _, v := range *CityList {
  68. res[v.Id] = v.Name
  69. }
  70. cache.SetJson(cacheKey, res, md.CfgCacheTime)
  71. }
  72. if len(keys) == 0 {
  73. return res
  74. }
  75. tmp := map[string]string{}
  76. for _, v := range keys {
  77. if val, ok := res[v]; ok {
  78. tmp[v] = val
  79. } else {
  80. tmp[v] = ""
  81. }
  82. }
  83. return tmp
  84. }