From 4fcb1f952c853295048c4c4b82fe33da4f9c0fe7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Fri, 14 Jul 2023 15:10:40 +0200 Subject: [PATCH] cache/redis: Rig up timeout with context --- cache/redis.go | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/cache/redis.go b/cache/redis.go index 3975e71..8911311 100644 --- a/cache/redis.go +++ b/cache/redis.go @@ -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 {