Simple cache with using different libraries.
go get github.com/rakunlabs/cacheResult of cache get, set and delete methods; stores could be force to types.
Get(ctx context.Context, key K) (V, bool, error)
Set(ctx context.Context, key K, value V) error
Delete(ctx context.Context, key K) errorAdditional function for help get-set together.
GetSet(ctx context.Context, key K, fn func() (V, error)) (V, error)Take gets and deletes a key atomically, so a value (for example a one-time
code) is consumed only once. The memory and redis stores support it; other
stores return cache.ErrTakeNotSupported.
Take(ctx context.Context, key K) (V, bool, error)To not use max items and ttl, you can pass empty config cache.WithStoreConfig(&memory.Config{}).
priceCache, err := cache.New[string, int](ctx,
memory.Store,
cache.WithStoreConfig(&memory.Config{
MaxItems: 100,
TTL: 10 * time.Minute,
}),
)
err := priceCache.Set(ctx, "key", 100)
v, ok, err := priceCache.Get(ctx, "key")Build a client with redis.NewClient (standalone or Redis Cluster, detected
automatically) or pass any existing redis.UniversalClient. The caller owns the
client and must close it.
redisClient, err := redis.NewClient(ctx, redis.ConnConfig{
Address: []string{"localhost:6379"},
})
if err != nil {
// handle error
}
defer redisClient.Close()
c, err := cache.New(ctx,
redis.Store(redisClient),
cache.WithStoreConfig(redis.Config{
TTL: 3 * time.Second,
KeyPrefix: "app_",
}),
)
if err != nil {
// handle error
}See store/redis/README.md for cluster detection and tests.