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"
)
const redisTimeout = 3 * time.Second
// RedisCache is the redis cache.
type RedisCache struct {
client *redis.Client
@ -22,7 +24,10 @@ func NewRedisCache(redisURL string, d time.Duration) (Cache, error) {
}
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 {
return nil, err
}
@ -34,13 +39,19 @@ func NewRedisCache(redisURL string, d time.Duration) (Cache, error) {
// Set saves an alert in the cache.
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
// and if the status matches.
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 {
return false, nil
} else if err != nil {