redis.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package cache
  2. import (
  3. "context"
  4. "time"
  5. "github.com/redis/go-redis/v9"
  6. )
  7. // Redis cache implement
  8. type Redis struct {
  9. client *redis.Client
  10. }
  11. // NewRedis 创建 redis 客户端
  12. func NewRedis(client *redis.Client, options *redis.Options) (*Redis, error) {
  13. if client == nil {
  14. client = redis.NewClient(options)
  15. }
  16. r := &Redis{
  17. client: client,
  18. }
  19. if err := r.connect(); err != nil {
  20. return nil, err
  21. }
  22. return r, nil
  23. }
  24. func (*Redis) String() string {
  25. return "redis"
  26. }
  27. func (r *Redis) connect() error {
  28. var err error
  29. _, err = r.client.Ping(context.TODO()).Result()
  30. return err
  31. }
  32. func (r *Redis) Get(key string) (string, error) {
  33. return r.client.Get(context.TODO(), key).Result()
  34. }
  35. func (r *Redis) Set(key string, value interface{}, expiration int) error {
  36. return r.client.Set(context.TODO(), key, value, time.Duration(expiration)*time.Second).Err()
  37. }
  38. func (r *Redis) Del(key string) error {
  39. return r.client.Del(context.TODO(), key).Err()
  40. }
  41. // HashGet 获取哈希
  42. func (r *Redis) HashGet(hk, key string) (string, error) {
  43. return r.client.HGet(context.TODO(), hk, key).Result()
  44. }
  45. // HashDel 删除哈希
  46. func (r *Redis) HashDel(hk, key string) error {
  47. return r.client.HDel(context.TODO(), hk, key).Err()
  48. }
  49. // HashSet 设置哈希
  50. func (r *Redis) HashSet(hk, key string, value interface{}) error {
  51. return r.client.HSet(context.TODO(), hk, key, value).Err()
  52. }
  53. // Increase 递增
  54. func (r *Redis) Increase(key string) error {
  55. return r.client.Incr(context.TODO(), key).Err()
  56. }
  57. // Decrease 递减
  58. func (r *Redis) Decrease(key string) error {
  59. return r.client.Decr(context.TODO(), key).Err()
  60. }
  61. // Expire 设置过期时间
  62. func (r *Redis) Expire(key string, dur time.Duration) error {
  63. return r.client.Expire(context.TODO(), key, dur).Err()
  64. }
  65. // GetClient 获取 redis client
  66. func (r *Redis) GetClient() *redis.Client {
  67. return r.client
  68. }