1
0
Fork 0
mirror of https://github.com/eosswedenorg/thalos synced 2026-06-16 04:24:56 +02:00

cache: adding factory method for redis

This commit is contained in:
Henrik Hautakoski 2024-07-23 16:31:40 +02:00
parent 2f31eb47d4
commit d1d4bf58b1
2 changed files with 61 additions and 0 deletions

View file

@ -5,18 +5,46 @@ import (
"time"
"github.com/go-redis/cache/v9"
"github.com/karlseguin/typed"
"github.com/redis/go-redis/v9"
)
type RedisStore struct {
c *cache.Cache
}
type options struct {
Stats bool
Size int
TTL time.Duration
}
func NewRedisStore(options *cache.Options) *RedisStore {
return &RedisStore{
c: cache.New(options),
}
}
func getOptions(opts typed.Typed) options {
return options{
Stats: opts.Bool("stats"),
Size: opts.IntOr("size", 1000),
TTL: time.Duration(opts.IntOr("ttl", 10)) * time.Minute,
}
}
func NewRedisFactory(client *redis.Client) Factory {
return func(opts typed.Typed) (Store, error) {
o := getOptions(opts)
return NewRedisStore(&cache.Options{
Redis: client,
StatsEnabled: o.Stats,
LocalCache: cache.NewTinyLFU(o.Size, o.TTL),
}), nil
}
}
func (s *RedisStore) Get(ctx context.Context, key string, value interface{}) error {
return s.c.Get(ctx, key, value)
}

View file

@ -6,6 +6,7 @@ import (
"time"
"github.com/go-redis/redismock/v9"
"github.com/karlseguin/typed"
redis_cache "github.com/go-redis/cache/v9"
"github.com/stretchr/testify/assert"
@ -16,6 +17,38 @@ type testItem struct {
Name string
}
func TestRedisStore_getOptionsDefaults(t *testing.T) {
opts := typed.Typed{}
expected := options{
Stats: false,
Size: 1000,
TTL: 10 * time.Minute,
}
actual := getOptions(opts)
assert.Equal(t, expected, actual)
}
func TestRedisStore_getOptions(t *testing.T) {
opts := typed.Typed{
"stats": true,
"size": 123,
"ttl": 60,
}
expected := options{
Stats: true,
Size: 123,
TTL: 60 * time.Minute,
}
actual := getOptions(opts)
assert.Equal(t, expected, actual)
}
func TestRedisStore_Set(t *testing.T) {
client, mock := redismock.NewClientMock()