2024-03-24 19:24:32 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-03-26 06:38:15 +00:00
|
|
|
"errors"
|
2024-03-24 19:24:32 +00:00
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type RedisCache struct {
|
|
|
|
ctx context.Context
|
|
|
|
rdb *redis.Client
|
|
|
|
}
|
|
|
|
|
2024-03-26 06:38:15 +00:00
|
|
|
func (r *RedisCache) Set(key string, value []byte, ttl time.Duration) error {
|
2024-03-24 19:24:32 +00:00
|
|
|
return r.rdb.Set(r.ctx, key, value, ttl).Err()
|
|
|
|
}
|
|
|
|
|
2024-03-26 06:38:15 +00:00
|
|
|
func (r *RedisCache) Get(key string) ([]byte, bool) {
|
|
|
|
val, err := r.rdb.Get(r.ctx, key).Bytes()
|
2024-03-24 19:24:32 +00:00
|
|
|
if err != nil {
|
2024-03-26 06:38:15 +00:00
|
|
|
if errors.Is(err, redis.Nil) {
|
2024-03-24 19:24:32 +00:00
|
|
|
log.Error().Err(err).Str("key", key).Msg("Couldn't request key from cache.")
|
|
|
|
}
|
2024-03-26 06:38:15 +00:00
|
|
|
return nil, false
|
2024-03-24 19:24:32 +00:00
|
|
|
} 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
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|