cachekit

package module
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 3 Imported by: 0

README

go-cache-kit

CI Go Reference License

Generic in-memory LRU cache with TTL, tags, eviction callbacks, stats, and thread safety for Go

Installation

go get github.com/philiprehberger/go-cache-kit

Usage

Basic Cache
import "github.com/philiprehberger/go-cache-kit"

cache := cachekit.New[string](1000, 5*time.Minute)

cache.Set("key", "value")
val, ok := cache.Get("key") // "value", true
Custom TTL per Entry
cache.Set("session", "abc123", cachekit.WithTTL(30*time.Minute))
cache.Set("temp", "data", cachekit.WithTTL(5*time.Second))
Tag-Based Invalidation
cache.Set("user:1", userData, cachekit.WithTags("users", "team-a"))
cache.Set("user:2", userData, cachekit.WithTags("users", "team-b"))
cache.Set("post:1", postData, cachekit.WithTags("posts", "team-a"))

removed := cache.InvalidateByTag("team-a") // 2
Compute-on-Miss
val := cache.GetOrSet("user:42", func() string {
    return fetchUserFromDB(42)
}, cachekit.WithTTL(10*time.Minute))
Batch Retrieval
results := cache.GetMany([]string{"user:1", "user:2", "user:3"})
// returns map[string]V with only the keys that exist and are not expired
Eviction Callback
cache.OnEvict(func(key string, value string) {
    log.Printf("evicted %s", key)
})
Cache Stats
stats := cache.Stats()
fmt.Printf("hits=%d misses=%d evictions=%d\n", stats.Hits, stats.Misses, stats.Evictions)
Conditional Deletion
removed := cache.DeleteWhere(func(key string, value string) bool {
    return strings.HasPrefix(key, "temp:")
})
LRU Eviction
cache := cachekit.New[string](100, 0) // no default TTL

// When full, least recently used entries are evicted
// Expired entries are preferred for eviction
Other Operations
cache.Has("key")      // check existence
cache.Delete("key")   // delete single entry
cache.Keys()          // list all non-expired keys
cache.Size()          // current entry count
cache.Clear()         // remove everything

API

Function / Method Description
New[V any](maxSize int, defaultTTL time.Duration) *Cache[V] Create a new LRU cache with max size and default TTL
(*Cache[V]).Set(key string, value V, opts ...SetOption) Add or update an entry in the cache
(*Cache[V]).Get(key string) (V, bool) Retrieve a value by key; returns false if missing or expired
(*Cache[V]).Has(key string) bool Check if a key exists and is not expired
(*Cache[V]).Delete(key string) bool Remove an entry by key; returns true if found
(*Cache[V]).GetOrSet(key string, factory func() V, opts ...SetOption) V Return cached value or compute and cache it on miss
(*Cache[V]).GetMany(keys []string) map[string]V Retrieve multiple values; omits missing or expired keys
(*Cache[V]).InvalidateByTag(tag string) int Remove all entries with the given tag; returns count removed
(*Cache[V]).DeleteWhere(predicate func(key string, value V) bool) int Remove all entries matching the predicate; returns count removed
(*Cache[V]).Clear() Remove all entries from the cache
(*Cache[V]).Size() int Return the current number of entries
(*Cache[V]).Keys() []string Return all non-expired keys
(*Cache[V]).OnEvict(fn func(key string, value V)) Register a callback for eviction events
(*Cache[V]).Stats() CacheStats Return hit, miss, and eviction counters
WithTTL(d time.Duration) SetOption Override the default TTL for a Set call
WithTags(tags ...string) SetOption Associate tags with an entry
CacheStats Struct with Hits, Misses, and Evictions counters (int64)
SetOption Functional option type for configuring Set calls

Development

go test ./...
go vet ./...

License

MIT

Documentation

Overview

Package cachekit provides a generic in-memory LRU cache with TTL and tag-based invalidation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[V any] struct {
	// contains filtered or unexported fields
}

Cache is a thread-safe in-memory LRU cache with TTL and tag support.

func New

func New[V any](maxSize int, defaultTTL time.Duration) *Cache[V]

New creates a new Cache with the given max size and default TTL. A zero TTL means entries don't expire by default.

func (*Cache[V]) Clear

func (c *Cache[V]) Clear()

Clear removes all entries.

func (*Cache[V]) Delete

func (c *Cache[V]) Delete(key string) bool

Delete removes an entry by key. Returns true if the key was found.

func (*Cache[V]) DeleteWhere added in v0.3.0

func (c *Cache[V]) DeleteWhere(predicate func(key string, value V) bool) int

DeleteWhere removes all entries matching the predicate. Returns the number of entries removed.

func (*Cache[V]) Get

func (c *Cache[V]) Get(key string) (V, bool)

Get retrieves a value from the cache. Returns the value and true if found and not expired.

func (*Cache[V]) GetMany added in v0.3.0

func (c *Cache[V]) GetMany(keys []string) map[string]V

GetMany returns all cached values for the given keys. Missing or expired keys are omitted.

func (*Cache[V]) GetOrSet added in v0.3.0

func (c *Cache[V]) GetOrSet(key string, factory func() V, opts ...SetOption) V

GetOrSet returns the cached value for key, or calls factory to compute and cache it.

func (*Cache[V]) Has

func (c *Cache[V]) Has(key string) bool

Has checks if a key exists and is not expired.

func (*Cache[V]) InvalidateByTag

func (c *Cache[V]) InvalidateByTag(tag string) int

InvalidateByTag removes all entries with the given tag. Returns the count removed.

func (*Cache[V]) Keys

func (c *Cache[V]) Keys() []string

Keys returns all non-expired keys.

func (*Cache[V]) OnEvict added in v0.3.0

func (c *Cache[V]) OnEvict(fn func(key string, value V))

OnEvict registers a callback that fires when entries are evicted (LRU or TTL).

func (*Cache[V]) Set

func (c *Cache[V]) Set(key string, value V, opts ...SetOption)

Set adds or updates an entry in the cache.

func (*Cache[V]) Size

func (c *Cache[V]) Size() int

Size returns the number of entries in the cache.

func (*Cache[V]) Stats added in v0.3.0

func (c *Cache[V]) Stats() CacheStats

Stats returns cache hit, miss, and eviction counters.

type CacheStats added in v0.3.0

type CacheStats struct {
	Hits      int64
	Misses    int64
	Evictions int64
}

CacheStats holds hit, miss, and eviction counters.

type SetOption

type SetOption func(*setConfig)

SetOption configures a Set call.

func WithTTL

func WithTTL(d time.Duration) SetOption

WithTTL overrides the default TTL for this entry.

func WithTags

func WithTags(tags ...string) SetOption

WithTags associates tags with the entry.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL