add redis ttl

This commit is contained in:
Max Lerebourg
2022-10-24 21:38:56 +02:00
parent ffcf4356fc
commit 0a186cf9a9
3 changed files with 47 additions and 48 deletions
+13 -16
View File
@@ -20,7 +20,6 @@ var redis simpleredis.SimpleRedis
var redisEnabled = false
func getDecisionLocalCache(clientIP string) (bool, error) {
banned, isCached := cache.Get(clientIP)
bannedString, isValid := banned.(string)
@@ -30,29 +29,28 @@ func getDecisionLocalCache(clientIP string) (bool, error) {
return false, fmt.Errorf("no cache data")
}
func SetDecisionLocalCache(clientIP string, value string, duration int64) {
func setDecisionLocalCache(clientIP string, value string, duration int64) {
cache.Set(clientIP, value, duration)
}
func DeleteDecisionLocalCache(clientIP string) {
func deleteDecisionLocalCache(clientIP string) {
cache.Del(clientIP)
}
func getDecisionRedisCache(clientIP string) (bool, error) {
banned, err := redis.Do("GET", clientIP, nil)
banned, err := redis.Get(clientIP)
bannedString := string(banned)
logger.Info(fmt.Sprintf("%v banned", bannedString))
if err == nil && len(bannedString) > 0 {
return bannedString == cacheBannedValue, nil
}
return false, fmt.Errorf("no cache data")
}
func SetDecisionRedisCache(clientIP string, value string, duration int64) {
redis.Do("SET", clientIP, []byte(value))
func setDecisionRedisCache(clientIP string, value string, duration int64) {
redis.Set(clientIP, []byte(value), duration)
}
func DeleteDecisionRedisCache(clientIP string) {
func deleteDecisionRedisCache(clientIP string) {
// err := rdb.Del(ctx, clientIP).Err()
// if err != nil {
// logger.Info("Error, could not delete in redis cache IP")
@@ -60,16 +58,15 @@ func DeleteDecisionRedisCache(clientIP string) {
// errors are not handled
}
func DeleteDecision(clientIP string) {
if redisEnabled {
DeleteDecisionRedisCache(clientIP)
deleteDecisionRedisCache(clientIP)
} else {
DeleteDecisionLocalCache(clientIP)
deleteDecisionLocalCache(clientIP)
}
}
// Get Decision check in the cache if the IP has the banned / not banned value.
// GetDecision check in the cache if the IP has the banned / not banned value.
// Otherwise return with an error to add the IP in cache if we are on.
func GetDecision(clientIP string) (bool, error) {
if redisEnabled {
@@ -88,14 +85,14 @@ func SetDecision(clientIP string, isBanned bool, duration int64) {
value = cacheNoBannedValue
}
if redisEnabled {
SetDecisionRedisCache(clientIP, value, duration)
setDecisionRedisCache(clientIP, value, duration)
} else {
SetDecisionLocalCache(clientIP, value, duration)
setDecisionLocalCache(clientIP, value, duration)
}
}
func InitRedisClient(host string, password string) {
logger.Debug("connect to redis")
redisEnabled = true
redis.Init(host)
logger.Debug("connect to redis")
}