Skip to content

Latest commit

 

History

History

cache

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

cache

Temporary key-value storage with a single Cache interface and two backends: Redis and in-memory.

Install

go get github.com/fatkulnurk/foundation/cache@v0.3.0

API

type Cache interface {
    Set(ctx context.Context, key string, value any, ttlSeconds int) error
    Get(ctx context.Context, key string) (string, error)
    Delete(ctx context.Context, key string) error
    Has(ctx context.Context, key string) (bool, error)
}
  • ttlSeconds <= 0 means no expiry (local) / Redis zero TTL semantics as implemented.
  • Keys are stored as Prefix + key when Config.Prefix is set.
  • Get returns cache.ErrNotFound when the key is missing or expired (local).

Local cache

cfg := &cache.Config{Prefix: "myapp:"}
c := cache.NewLocalCache(cfg)
if lc, ok := c.(*cache.LocalCache); ok {
    defer lc.Close() // stops background janitor
}

_ = c.Set(ctx, "user:1", "Ada", 60)
v, err := c.Get(ctx, "user:1")

Suitable for tests, single-process apps, and data that must not be shared across instances. Expired keys are removed on access and by a background janitor.

Redis cache

import "github.com/redis/go-redis/v9"

rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
c := cache.NewRedisCache(&cache.Config{Prefix: "myapp:"}, rdb)

_ = c.Set(ctx, "user:1", "Ada", 60)

Use Redis when multiple processes/servers must share the same cache.

Config

Field Env (via LoadConfig) Description
Prefix CACHE_PREFIX Optional key prefix (e.g. myapp:)
cfg := cache.LoadConfig()

When to use which

Local Redis
Shared across nodes No Yes
Extra dependency None Redis server
Best for Dev, tests, single instance Production multi-instance

See also