vegvisir/pkg/cache/redis_datastore.go
Piotr Biernat ea6c90236a
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
Renamed src/ to pkg/
Added cache with base redis support
Added profiling in main.go
2021-07-23 16:10:37 +02:00

58 lines
1.3 KiB
Go

// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// 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
}),
cache: make(map[string]interface{}),
}
}
type RedisDatastore struct {
client *redis.Client
cache map[string]interface{}
}
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
}
// ds.cache[key] = data
return nil
}
func (ds *RedisDatastore) GetKey(key string) (interface{}, error) {
// if data, ok := ds.cache[key]; ok {
// return data, nil
// }
data, err := ds.client.Get(key).Result()
if err != nil {
return nil, err
}
return data, nil
}