cache.go 2.0 KB

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