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 (
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/go-redis/redis"
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewRedisDatastore(host string, port int) *RedisDatastore {
|
|
|
|
return &RedisDatastore{
|
|
|
|
client: redis.NewClient(&redis.Options{
|
|
|
|
Addr: host + ":" + strconv.Itoa(port),
|
|
|
|
Password: "", // FIXME: use env or param
|
|
|
|
DB: 0, // FIXME: use env or param
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type RedisDatastore struct {
|
|
|
|
client *redis.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
func (ds *RedisDatastore) IsConnected() bool {
|
|
|
|
_, err := ds.client.Ping().Result()
|
|
|
|
|
|
|
|
return err == nil
|
|
|
|
}
|