mirror of
https://codeberg.org/Codeberg/pages-server.git
synced 2026-09-19 15:14:14 +00:00
Add redis for caching, first try during a train ride so expect it to not be working yet
This commit is contained in:
Vendored
+2
-2
@@ -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)
|
||||
}
|
||||
|
||||
Vendored
+26
-2
@@ -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()}
|
||||
}
|
||||
|
||||
Vendored
+47
@@ -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
|
||||
}),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user