Add redis for caching, first try during a train ride so expect it to not be working yet

This commit is contained in:
Moritz Marquardt 2024-03-24 20:24:32 +01:00
parent b8b9886ee1
commit 5b6eecc75f
12 changed files with 149 additions and 32 deletions

View file

@ -4,7 +4,7 @@ import "time"
// ICache is an interface that defines how the pages server interacts with the cache.
type ICache interface {
Set(key string, value interface{}, ttl time.Duration) error
Get(key string) (interface{}, bool)
Set(key string, value string, ttl time.Duration) error
Get(key string) (string, bool)
Remove(key string)
}

View file

@ -1,7 +1,31 @@
package cache
import "github.com/OrlovEvgeny/go-mcache"
import (
"github.com/OrlovEvgeny/go-mcache"
"time"
)
type MCache struct {
mcache *mcache.CacheDriver
}
func (m *MCache) Set(key string, value string, ttl time.Duration) error {
return m.mcache.Set(key, value, ttl)
}
func (m *MCache) Get(key string) (string, bool) {
val, ok := m.mcache.Get(key)
if ok {
return val.(string), true
} else {
return "", false
}
}
func (m *MCache) Remove(key string) {
m.mcache.Remove(key)
}
func NewInMemoryCache() ICache {
return mcache.New()
return &MCache{mcache.New()}
}

47
server/cache/redis.go vendored Normal file
View file

@ -0,0 +1,47 @@
package cache
import (
"context"
"github.com/redis/go-redis/v9"
"github.com/rs/zerolog/log"
"time"
)
type RedisCache struct {
ctx context.Context
rdb *redis.Client
}
func (r *RedisCache) Set(key string, value string, ttl time.Duration) error {
return r.rdb.Set(r.ctx, key, value, ttl).Err()
}
func (r *RedisCache) Get(key string) (string, bool) {
val, err := r.rdb.Get(r.ctx, key).Result()
if err != nil {
if err == redis.Nil {
log.Error().Err(err).Str("key", key).Msg("Couldn't request key from cache.")
}
return "", false
} else {
return val, true
}
}
func (r *RedisCache) Remove(key string) {
err := r.rdb.Del(r.ctx, key).Err()
if err == nil {
log.Error().Err(err).Str("key", key).Msg("Couldn't delete key from cache.")
}
}
func NewRedisCache() ICache {
return &RedisCache{
context.Background(),
redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
}),
}
}