mirror of
https://codeberg.org/Codeberg/pages-server.git
synced 2025-05-14 01:07:10 +02:00
Add redis for caching, first try during a train ride so expect it to not be working yet
This commit is contained in:
parent
b8b9886ee1
commit
5b6eecc75f
12 changed files with 149 additions and 32 deletions
47
server/cache/redis.go
vendored
Normal file
47
server/cache/redis.go
vendored
Normal 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
|
||||
}),
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue