cache/redis: Rig up timeout with context

This commit is contained in:
Thorben Günther 2023-07-14 15:10:40 +02:00
parent e0e1281ec3
commit 4fcb1f952c
No known key found for this signature in database
GPG key ID: 415CD778D8C5AFED

17
cache/redis.go vendored
View file

@ -7,6 +7,8 @@ import (
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
const redisTimeout = 3 * time.Second
// RedisCache is the redis cache. // RedisCache is the redis cache.
type RedisCache struct { type RedisCache struct {
client *redis.Client client *redis.Client
@ -22,7 +24,10 @@ func NewRedisCache(redisURL string, d time.Duration) (Cache, error) {
} }
rdb := redis.NewClient(ropts) rdb := redis.NewClient(ropts)
err = rdb.Ping(context.Background()).Err() ctx, cancel := context.WithTimeout(context.TODO(), redisTimeout)
defer cancel()
err = rdb.Ping(ctx).Err()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -34,13 +39,19 @@ func NewRedisCache(redisURL string, d time.Duration) (Cache, error) {
// Set saves an alert in the cache. // Set saves an alert in the cache.
func (c *RedisCache) Set(fingerprint string, status string) error { func (c *RedisCache) Set(fingerprint string, status string) error {
return c.client.SetEx(context.Background(), fingerprint, status, c.duration).Err() ctx, cancel := context.WithTimeout(context.TODO(), redisTimeout)
defer cancel()
return c.client.SetEx(ctx, fingerprint, status, c.duration).Err()
} }
// Contains checks if an alert with a given fingerprint is in the cache // Contains checks if an alert with a given fingerprint is in the cache
// and if the status matches. // and if the status matches.
func (c *RedisCache) Contains(fingerprint string, status string) (bool, error) { func (c *RedisCache) Contains(fingerprint string, status string) (bool, error) {
val, err := c.client.Get(context.Background(), fingerprint).Result() ctx, cancel := context.WithTimeout(context.TODO(), redisTimeout)
defer cancel()
val, err := c.client.Get(ctx, fingerprint).Result()
if err == redis.Nil { if err == redis.Nil {
return false, nil return false, nil
} else if err != nil { } else if err != nil {