golang 的 rabbitmq 消费项目
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

db_province.go 2.2 KiB

1年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 ProvinceGetAll() (*[]model.Province, error) {
  9. var provinceList []model.Province
  10. if err := Db.Cols("id,name").Find(&provinceList); err != nil {
  11. return nil, logx.Error(err)
  12. }
  13. return &provinceList, nil
  14. }
  15. // 获取一条记录
  16. func ProvinceGetOne(key string) (*model.Province, error) {
  17. var province model.Province
  18. if has, err := Db.Where("`id`=?", key).Get(&province); err != nil || has == false {
  19. if has == false {
  20. return &province, nil
  21. }
  22. return nil, logx.Error(err)
  23. }
  24. return &province, nil
  25. }
  26. func ProvinceGetOneByName(name string) (*model.Province, error) {
  27. var province model.Province
  28. if has, err := Db.Where("name LIKE ?", "%"+name+"%").Get(&province); err != nil || has == false {
  29. if has == false {
  30. return &province, nil
  31. }
  32. return nil, logx.Error(err)
  33. }
  34. return &province, nil
  35. }
  36. //单条记录获取DB
  37. func ProvinceGetWithDb(HKey string) string {
  38. cacheKey := md.OfficialProvinceCacheKey
  39. get, err := cache.HGetString(cacheKey, HKey)
  40. if err != nil || get == "" {
  41. province, err := ProvinceGetOne(HKey)
  42. if err != nil || province == nil {
  43. _ = logx.Error(err)
  44. return ""
  45. }
  46. // key是否存在
  47. cacheKeyExist := false
  48. if cache.Exists(cacheKey) {
  49. cacheKeyExist = true
  50. }
  51. // 设置缓存
  52. _, err = cache.HSet(cacheKey, HKey, province.Name)
  53. if err != nil {
  54. _ = logx.Error(err)
  55. return ""
  56. }
  57. if !cacheKeyExist { // 如果是首次设置 设置过期时间
  58. _, err := cache.Expire(cacheKey, md.CfgCacheTime)
  59. if err != nil {
  60. _ = logx.Error(err)
  61. return ""
  62. }
  63. }
  64. return province.Name
  65. }
  66. return get
  67. }
  68. func ProvinceFindWithDb(keys ...string) map[string]string {
  69. res := map[string]string{}
  70. cacheKey := md.OfficialProvinceCacheKey
  71. err := cache.GetJson(cacheKey, &res)
  72. if err != nil || len(res) == 0 {
  73. provinceList, _ := ProvinceGetAll()
  74. if provinceList == nil {
  75. return nil
  76. }
  77. for _, v := range *provinceList {
  78. res[v.Id] = v.Name
  79. }
  80. cache.SetJson(cacheKey, res, md.CfgCacheTime)
  81. }
  82. if len(keys) == 0 {
  83. return res
  84. }
  85. tmp := map[string]string{}
  86. for _, v := range keys {
  87. if val, ok := res[v]; ok {
  88. tmp[v] = val
  89. } else {
  90. tmp[v] = ""
  91. }
  92. }
  93. return tmp
  94. }