diff --git a/internal/cache/redis_store.go b/internal/cache/redis_store.go index 54d7f4d..d8101ad 100644 --- a/internal/cache/redis_store.go +++ b/internal/cache/redis_store.go @@ -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) } diff --git a/internal/cache/redis_store_test.go b/internal/cache/redis_store_test.go index f12cc33..7d4c7c3 100644 --- a/internal/cache/redis_store_test.go +++ b/internal/cache/redis_store_test.go @@ -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()