redis.go 880 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package cache
  2. import (
  3. "context"
  4. "github.com/go-redis/redis/v8"
  5. "time"
  6. )
  7. var ctx = context.Background()
  8. type RedisCache struct {
  9. rdb *redis.Client
  10. }
  11. func RedisCacheInit(conf *redis.Options) *RedisCache {
  12. c := &RedisCache{}
  13. c.rdb = redis.NewClient(conf)
  14. return c
  15. }
  16. func (c *RedisCache) Get(key string, value interface{}) error {
  17. data, err := c.rdb.Get(ctx, key).Result()
  18. if err != nil {
  19. return err
  20. }
  21. err1 := DecodeValue(data, value)
  22. return err1
  23. }
  24. func (c *RedisCache) Set(key string, value interface{}, exp int) error {
  25. str, err := EncodeValue(value)
  26. if err != nil {
  27. return err
  28. }
  29. if exp <= 0 {
  30. exp = MaxTimeOut
  31. }
  32. _, err1 := c.rdb.Set(ctx, key, str, time.Duration(exp)*time.Second).Result()
  33. return err1
  34. }
  35. func (c *RedisCache) Gc() error {
  36. return nil
  37. }
  38. func NewRedis(conf *redis.Options) *RedisCache {
  39. cache := RedisCacheInit(conf)
  40. return cache
  41. }