cache icon indicating copy to clipboard operation
cache copied to clipboard

Export rediser interface to make cache transparent

Open lirtistan opened this issue 1 year ago • 0 comments

Hi,

i have written an http middleware for handling sessions, it has multiple storage backends.

One of those backends is Redis, i want to use go-redis/cache as the main driver for storing objects, but the rediser interface used by the contructor is package private, so i have to implement my own (but this is bad practice).

It whould be nice if the rediser interface is exported by go-redis/cache itself, just to eliminate the layer of indirection.

My current solution:

func RedisStorage(*cache.Cache) {}
// ... somewhere else in the app ...
rdb := redis.NewClient(nil)
cache := cache.New(&cache.Options{
  Redis: rdb,
})
RedisStorage(cache)

How it should be:

func RedisStorage(cache.Rediser) {}
// ... somewhere else in the app ...
rdb1 := redis.NewClient(nil)
rdb2 := redis.NewClusterClient(nil)
rdb3 := redis.NewRing(nil)
RedisStorage(rdb1)
RedisStorage(rdb2)
RedisStorage(rdb3)

A simple exported type alias to cache.rediser can fix that problem without breaking changes.

type rediser interface {
	Set(ctx context.Context, key string, value interface{}, ttl time.Duration) *redis.StatusCmd
	SetXX(ctx context.Context, key string, value interface{}, ttl time.Duration) *redis.BoolCmd
	SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) *redis.BoolCmd

	Get(ctx context.Context, key string) *redis.StringCmd
	Del(ctx context.Context, keys ...string) *redis.IntCmd
}

type Rediser = rediser // <-- to make it transparent

lirtistan avatar Jan 02 '25 07:01 lirtistan