github.com/thanos-io/thanos@v0.32.5/pkg/cache/redis.go (about) 1 // Copyright (c) The Thanos Authors. 2 // Licensed under the Apache License 2.0. 3 4 package cache 5 6 import ( 7 "context" 8 "time" 9 10 "github.com/go-kit/log" 11 "github.com/go-kit/log/level" 12 "github.com/prometheus/client_golang/prometheus" 13 "github.com/prometheus/client_golang/prometheus/promauto" 14 "github.com/thanos-io/thanos/pkg/cacheutil" 15 ) 16 17 // RedisCache is a redis cache. 18 type RedisCache struct { 19 logger log.Logger 20 redisClient *cacheutil.RedisClient 21 name string 22 23 // Metrics. 24 requests prometheus.Counter 25 hits prometheus.Counter 26 } 27 28 // NewRedisCache makes a new RedisCache. 29 func NewRedisCache(name string, logger log.Logger, redisClient *cacheutil.RedisClient, reg prometheus.Registerer) *RedisCache { 30 c := &RedisCache{ 31 logger: logger, 32 redisClient: redisClient, 33 name: name, 34 } 35 36 c.requests = promauto.With(reg).NewCounter(prometheus.CounterOpts{ 37 Name: "thanos_cache_redis_requests_total", 38 Help: "Total number of items requests to redis.", 39 ConstLabels: prometheus.Labels{"name": name}, 40 }) 41 42 c.hits = promauto.With(reg).NewCounter(prometheus.CounterOpts{ 43 Name: "thanos_cache_redis_hits_total", 44 Help: "Total number of items requests to the cache that were a hit.", 45 ConstLabels: prometheus.Labels{"name": name}, 46 }) 47 48 level.Info(logger).Log("msg", "created redis cache") 49 50 return c 51 } 52 53 // Store data identified by keys. 54 func (c *RedisCache) Store(data map[string][]byte, ttl time.Duration) { 55 c.redisClient.SetMulti(data, ttl) 56 } 57 58 // Fetch fetches multiple keys and returns a map containing cache hits, along with a list of missing keys. 59 // In case of error, it logs and return an empty cache hits map. 60 func (c *RedisCache) Fetch(ctx context.Context, keys []string) map[string][]byte { 61 c.requests.Add(float64(len(keys))) 62 results := c.redisClient.GetMulti(ctx, keys) 63 c.hits.Add(float64(len(results))) 64 return results 65 } 66 67 func (c *RedisCache) Name() string { 68 return c.name 69 }