cache.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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) GetCacheNum(ctx context.Context, key string) (num int, err error) {
  56. num, err = global.GVA_REDIS.Get(ctx, key).Int()
  57. if err != nil {
  58. if err == redis.Nil {
  59. return 0, nil
  60. }
  61. return 0, err
  62. }
  63. return num, err
  64. }
  65. func (s *Cache) ExistsKey(ctx context.Context, key string) (bool, error) {
  66. isNull, err := global.GVA_REDIS.Exists(ctx, key).Result()
  67. if err != nil {
  68. return false, err
  69. }
  70. if isNull == 0 {
  71. return false, nil
  72. } else {
  73. return true, nil
  74. }
  75. }