From 3533283f091c72cfe9ccfc2c3c8465f96584397b Mon Sep 17 00:00:00 2001 From: jano3 <jano@uafrica.com> Date: Mon, 23 May 2022 15:57:43 +0200 Subject: [PATCH] Added function to set a redis object with specific expiration. --- redis/redis.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/redis/redis.go b/redis/redis.go index ff44a4b..1f8545e 100644 --- a/redis/redis.go +++ b/redis/redis.go @@ -91,6 +91,28 @@ func (r ClientWithHelpers) SetObjectByKey(key string, object interface{}) { } } +func (r ClientWithHelpers) SetObjectByKeyWithExpiry(key string, object interface{}, expiration time.Duration) { + if !r.IsConnected() { + return + } + + jsonBytes, err := json.Marshal(object) + if err != nil { + logs.ErrorWithMsg("Error marshalling object to Redis: %s", err) + return + } + + _, err = r.Client.Set(ctx, key, string(jsonBytes), expiration).Result() + if err != nil { + logs.ErrorWithMsg(fmt.Sprintf("Error setting value to Redis for key: %s", key), err) + + /* Prevent further calls in this execution from trying to connect and also timeout */ + if strings.HasSuffix(err.Error(), "i/o timeout") { + r.Available = false + } + } +} + func (r ClientWithHelpers) SetObjectByKeyIndefinitely(key string, object interface{}) { if !r.IsConnected() { return -- GitLab