go-micro.dev/v5@v5.12.0/cache/redis/redis.go (about)

     1  package redis
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	rclient "github.com/go-redis/redis/v8"
     8  	"go-micro.dev/v5/cache"
     9  )
    10  
    11  // NewRedisCache returns a new redis cache.
    12  func NewRedisCache(opts ...cache.Option) cache.Cache {
    13  	options := cache.NewOptions(opts...)
    14  	return &redisCache{
    15  		opts:   options,
    16  		client: newUniversalClient(options),
    17  	}
    18  }
    19  
    20  type redisCache struct {
    21  	opts   cache.Options
    22  	client rclient.UniversalClient
    23  }
    24  
    25  func (c *redisCache) Get(ctx context.Context, key string) (interface{}, time.Time, error) {
    26  	val, err := c.client.Get(ctx, key).Bytes()
    27  	if err != nil && err == rclient.Nil {
    28  		return nil, time.Time{}, cache.ErrKeyNotFound
    29  	} else if err != nil {
    30  		return nil, time.Time{}, err
    31  	}
    32  
    33  	dur, err := c.client.TTL(ctx, key).Result()
    34  	if err != nil {
    35  		return nil, time.Time{}, err
    36  	}
    37  	if dur == -1 {
    38  		return val, time.Unix(1<<63-1, 0), nil
    39  	}
    40  	if dur == -2 {
    41  		return val, time.Time{}, cache.ErrItemExpired
    42  	}
    43  
    44  	return val, time.Now().Add(dur), nil
    45  }
    46  
    47  func (c *redisCache) Put(ctx context.Context, key string, val interface{}, dur time.Duration) error {
    48  	return c.client.Set(ctx, key, val, dur).Err()
    49  }
    50  
    51  func (c *redisCache) Delete(ctx context.Context, key string) error {
    52  	return c.client.Del(ctx, key).Err()
    53  }
    54  
    55  func (m *redisCache) String() string {
    56  	return "redis"
    57  }