cache.go 2.1 KB

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