go-pkgz / lcw

Loading Cache Wrapper
https://go-pkgz.umputun.dev/lcw/
MIT License
20 stars 5 forks source link
cache caching-library go golang-library

Loading Cache Wrapper Build Status Coverage Status godoc

The library adds a thin layer on top of lru\expirable 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:

Install and update

go get -u github.com/go-pkgz/lcw/v2

Usage

package main

import (
    "github.com/go-pkgz/lcw/v2"
)

func main() {
    o := lcw.NewOpts[int]()
    cache, err := lcw.NewLruCache(o.MaxKeys(500), o.MaxCacheSize(65536), o.MaxValSize(200), o.MaxKeySize(32))
    if err != nil {
        panic("failed to create cache")
    }
    defer cache.Close()

    val, err := cache.Get("key123", func() (int, error) {
        res, err := getDataFromSomeSource(params) // returns int
        return res, err
    })

    if err != nil {
        panic("failed to get data")
    }

    s := val // cached value
}

Cache with URI

Cache can be created with URIs:

Scoped cache

Scache provides a wrapper on top of all implementations of LoadingCache with a number of special features:

  1. Key is not a string, but a composed type made from partition, key-id and list of scopes (tags).
  2. Value type limited to []byte
  3. Added Flush method for scoped/tagged invalidation of multiple records in a given partition
  4. A simplified interface with Get, Stat, Flush and Close only.

Details