redis.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package cache
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/go-redis/redis/v8"
  6. "time"
  7. )
  8. type rediscli struct {
  9. c *redis.Client
  10. }
  11. type Options redis.Options
  12. func (c *rediscli) Set(ctx context.Context, key, val string, t time.Duration) (bool, error) {
  13. _, err := c.c.Set(ctx, key, val, t).Result()
  14. if err != nil {
  15. return false, err
  16. }
  17. return true, nil
  18. }
  19. func (c *rediscli) Get(ctx context.Context, key string) (string, error) {
  20. v, err := c.c.Get(ctx, key).Result()
  21. if err != nil {
  22. if errors.Is(err, redis.Nil) {
  23. return "", ErrorCacheNotFound
  24. }
  25. return "", err
  26. }
  27. return v, nil
  28. }
  29. func (c *rediscli) Delete(ctx context.Context, key string) (bool, error) {
  30. _, err := c.c.Del(ctx, key).Result()
  31. if err != nil {
  32. return false, err
  33. }
  34. return true, nil
  35. }
  36. func NewRedis(o *Options) Cache {
  37. return &rediscli{c: newRedisClient(o)}
  38. }
  39. func newRedisClient(o *Options) *redis.Client {
  40. redisClient := redis.NewClient((*redis.Options)(o))
  41. timeout, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  42. defer cancel()
  43. _, err := redisClient.Ping(timeout).Result()
  44. if err != nil {
  45. panic(err)
  46. }
  47. return redisClient
  48. }