cache.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package cache
  2. import (
  3. "context"
  4. "github.com/go-redis/redis/v8"
  5. "log-server/global"
  6. "time"
  7. )
  8. const (
  9. TemporaryTaskPcCode = "%s:temporaryTaskPcCode:%s"
  10. UploadImageNum = "%s:UploadImageNum:%d"
  11. ComputerEfficiency = "%s:ComputerEfficiency:%s"
  12. )
  13. type Cache struct {
  14. }
  15. func (s *Cache) DelBatheHsCache(ctx context.Context, key string) (err error) {
  16. keys, err := global.GVA_REDIS.HKeys(ctx, key).Result()
  17. if err != nil {
  18. if err == redis.Nil {
  19. return nil
  20. }
  21. return
  22. }
  23. global.GVA_REDIS.HDel(ctx, key, keys...)
  24. //for _, v := range keys {
  25. // global.GVA_REDIS.HDel(ctx, key, v)
  26. //}
  27. return
  28. }
  29. func (s *Cache) DelBatheCache(ctx context.Context, key string) (err error) {
  30. keys, err := global.GVA_REDIS.Keys(ctx, key).Result()
  31. if err != nil {
  32. if err == redis.Nil {
  33. return nil
  34. }
  35. return
  36. }
  37. global.GVA_REDIS.Del(ctx, keys...)
  38. //for _, v := range keys {
  39. // fmt.Println(v)
  40. // global.GVA_REDIS.Del(ctx, v)
  41. //}
  42. return
  43. }
  44. func (s *Cache) GetCacheKeys(ctx context.Context, keys string) (key []string, err error) {
  45. key, err = global.GVA_REDIS.Keys(ctx, keys).Result()
  46. return
  47. }
  48. func (s *Cache) SetCacheNum(ctx context.Context, key string) (err error) {
  49. bl, err := s.ExistsKey(ctx, key)
  50. if err != nil {
  51. return err
  52. }
  53. if !bl {
  54. err = global.GVA_REDIS.Set(ctx, key, 1, time.Hour*48).Err()
  55. return err
  56. } else {
  57. err = global.GVA_REDIS.Incr(ctx, key).Err()
  58. return err
  59. }
  60. }
  61. func (s *Cache) SetCacheStr(ctx context.Context, key string, value interface{}) (err error) {
  62. err = global.GVA_REDIS.Set(ctx, key, value, time.Hour*30).Err()
  63. return err
  64. }
  65. func (s *Cache) GetCacheNum(ctx context.Context, key string) (num int, err error) {
  66. num, err = global.GVA_REDIS.Get(ctx, key).Int()
  67. if err != nil {
  68. if err == redis.Nil {
  69. return 0, nil
  70. }
  71. return 0, err
  72. }
  73. return num, err
  74. }
  75. func (s *Cache) GetCacheStr(ctx context.Context, key string) (str string, err error) {
  76. str, err = global.GVA_REDIS.Get(ctx, key).Result()
  77. if err != nil {
  78. if err == redis.Nil {
  79. return "", nil
  80. }
  81. return "", err
  82. }
  83. return str, err
  84. }
  85. func (s *Cache) ExistsKey(ctx context.Context, key string) (bool, error) {
  86. isNull, err := global.GVA_REDIS.Exists(ctx, key).Result()
  87. if err != nil {
  88. return false, err
  89. }
  90. if isNull == 0 {
  91. return false, nil
  92. } else {
  93. return true, nil
  94. }
  95. }