2021-07-23 16:10:37 +02:00
|
|
|
// ___ ____ ___ ___
|
|
|
|
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
|
|
|
|
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
|
|
|
|
// \ / | _ | _ | \ / || __ | || ||\\
|
|
|
|
// \/ |___ |___ | \/ || ____| || || \\
|
|
|
|
//
|
|
|
|
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
|
|
|
|
// Repo: https://git.pbiernat.dev/golang/vegvisir
|
|
|
|
|
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
2021-11-15 16:33:31 +01:00
|
|
|
"github.com/go-redis/redis"
|
2021-11-10 01:36:33 +01:00
|
|
|
"log"
|
|
|
|
"os"
|
2021-07-23 16:10:37 +02:00
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// NewRedisDatastore function
|
2021-11-10 01:36:33 +01:00
|
|
|
func NewRedisDatastore(host, password, db string, port int) *RedisDatastore {
|
|
|
|
dbNum, err := strconv.Atoi(db)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Config: Invalid redis database!")
|
|
|
|
|
|
|
|
os.Exit(1) // FIXME: move up so in main we use os.Exit ONLY!
|
|
|
|
}
|
2021-07-23 16:10:37 +02:00
|
|
|
return &RedisDatastore{
|
|
|
|
client: redis.NewClient(&redis.Options{
|
|
|
|
Addr: host + ":" + strconv.Itoa(port),
|
2021-11-10 01:36:33 +01:00
|
|
|
Password: password,
|
|
|
|
DB: dbNum,
|
2021-07-23 16:10:37 +02:00
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// RedisDatastore class
|
2021-07-23 16:10:37 +02:00
|
|
|
type RedisDatastore struct {
|
|
|
|
client *redis.Client
|
|
|
|
}
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// SetKey function
|
2021-07-23 16:10:37 +02:00
|
|
|
func (ds *RedisDatastore) SetKey(key string, data interface{}, ttl int) error {
|
|
|
|
err := ds.client.Set(key, data, time.Duration(ttl)*time.Second).Err()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// GetKey function
|
2021-07-23 16:10:37 +02:00
|
|
|
func (ds *RedisDatastore) GetKey(key string) (interface{}, error) {
|
|
|
|
data, err := ds.client.Get(key).Result()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return data, nil
|
|
|
|
}
|
2021-07-24 17:46:22 +02:00
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// IsConnected function
|
2021-07-24 17:46:22 +02:00
|
|
|
func (ds *RedisDatastore) IsConnected() bool {
|
|
|
|
_, err := ds.client.Ping().Result()
|
|
|
|
|
|
|
|
return err == nil
|
|
|
|
}
|