pages-server/server/cache/redis.go

48 lines
982 B
Go
Raw Normal View History

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
}),
}
}