sacrebleu-dns/utils/redis.go

70 lines
1.8 KiB
Go
Raw Normal View History

2020-12-13 04:01:04 +01:00
package utils
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/go-redis/redis/v8"
"github.com/sirupsen/logrus"
)
2020-12-14 23:20:24 +01:00
//Redis context
2020-12-13 04:01:04 +01:00
var ctx = context.Background()
2020-12-14 23:20:24 +01:00
//Redis client as global var
2020-12-13 04:01:04 +01:00
var redisDb *redis.Client
//RedisDatabase : Initialize the Redis Database
2020-12-14 23:20:24 +01:00
//Requires a conf struct
//Return a *redis.Client
2020-12-13 04:01:04 +01:00
func RedisDatabase(conf *Conf) *redis.Client {
logrus.WithFields(logrus.Fields{"ip": conf.Redis.IP, "port": conf.Redis.Port}).Infof("REDIS : Connection to DB")
2020-12-13 04:01:04 +01:00
rdb := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%v", conf.Redis.IP, conf.Redis.Port),
2020-12-13 04:01:04 +01:00
Password: conf.Redis.Password,
DB: conf.Redis.Db,
2020-12-14 23:20:24 +01:00
}) //Connect to the DB
2020-12-13 04:01:04 +01:00
//Test Redis connection
err := rdb.Set(ctx, "alive", 1, 0).Err()
2020-12-13 19:43:31 +01:00
CheckErr(err)
2020-12-13 04:01:04 +01:00
alive, err := rdb.Get(ctx, "alive").Result()
CheckErr(err)
if alive != "1" {
logrus.WithFields(logrus.Fields{"alive": alive}).Panic("REDIS : Test not passed. alive != 1")
}
CheckErr(err)
logrus.WithFields(logrus.Fields{"db": conf.Redis.Db}).Info("REDIS : Successfull connection")
redisDb = rdb
return rdb
}
2020-12-14 23:20:24 +01:00
//Check for a record in the Redis database
//Requires the redis key (as string) and the record to check (struct)
//Return a Record (struct) and error (if any)
2020-12-13 04:01:04 +01:00
func redisCheckForRecord(redisKey string, entry Record) (Record, error) {
val, err := redisDb.Get(ctx, redisKey).Result()
//If Record in Redis cache
if err == nil {
err := json.Unmarshal([]byte(val), &entry)
logrus.Debugf("REDIS : %s => %s", redisKey, entry.Content)
return entry, err
}
return entry, redis.Nil
2020-12-13 04:01:04 +01:00
}
2020-12-14 23:20:24 +01:00
//Add a record in the Redis database
//Return an error (if any)
2020-12-13 04:01:04 +01:00
func redisSet(c *redis.Client, key string, ttl time.Duration, value interface{}) error {
p, err := json.Marshal(value)
if err != nil {
return err
}
return c.Set(ctx, key, p, ttl).Err()
}