Loading Cache Wrapper

The library adds a thin layer on top of lru cache and patrickmn/go-cache.
| Cache name | Constructor | Defaults | Description |
|---|---|---|---|
| LruCache | lcw.NewLruCache | keys=1000 | LRU cache with limits |
| ExpirableCache | lcw.NewExpirableCache | keys=1000, ttl=5m | TTL cache with limits |
| RedisCache | lcw.NewRedisCache | ttl=5m | Redis cache with limits |
| Nop | lcw.NewNopCache | Do-nothing cache |
Main features:
- LoadingCache (guava style)
- Limit maximum cache size (in bytes)
- Limit maximum key size
- Limit maximum size of a value
- Limit number of keys
- TTL support (
ExpirableCacheandRedisCache) - Callback on eviction event (not supported in
RedisCache) - Functional style invalidation
- Functional options
- Sane defaults
Install and update
go get -u github.com/go-pkgz/lcw
Usage
cache := lcw.NewLruCache(lcw.MaxKeys(500), lcw.MaxCacheSize(65536), lcw.MaxValSize(200), lcw.MaxKeySize(32))
val, err := cache.Get("key123", func() (lcw.Value, error) {
res, err := getDataFromSomeSource(params) // returns string
return res, err
})
if err != nil {
panic("failed to get data")
}
s := val.(string) // cached value
Cache with URI
Cache can be created with URIs:
mem://lru?max_key_size=10&max_val_size=1024&max_keys=50&max_cache_size=64000- creates LRU cache with given limitsmem://expirable?ttl=30s&max_key_size=10&max_val_size=1024&max_keys=50&max_cache_size=64000- create expirable cacheredis://10.0.0.1:1234?db=16&password=qwerty&network=tcp4&dial_timeout=1s&read_timeout=5s&write_timeout=3s- create redis cachenop://- create Nop cache
Scoped cache
Scache provides a wrapper on top of all implementations of LoadingCache with a number of special features:
- Key is not a string but a composed type made from partition, key-id and list of scopes (tags).
- Value type limited to
[]byte - Added
Flushmethod for scoped/tagged invalidation of multiple records in a given partition - Simplified interface with Get, Stat and Flush only.
Details
- All byte-size limits (MaxCacheSize and MaxValSize) only work for values implementing
lcw.Sizerinterface. - Negative limits (max options) rejected
lgr.Valuewrapsinterface{}and should be converted back to the concrete type.- The implementation started as a part of remark42 and later on moved to go-pkgz/rest library and finaly generalized to become
lcw.