Skip to content

Thread safe cache for Go with eviction policies.

License

Notifications You must be signed in to change notification settings

twharmon/gocache

Repository files navigation

Gocache

Go Reference codecov

Thread safe, generic, in-memory cache for Golang with optional TTL settings.

Documentation

For full documentation see pkg.go.dev.

Usage

Basic

package main

import (
	"github.com/twharmon/gocache"
)

func main() {
    // Create a basic eviction policy.
    ep := cocache.NewEvictionPolicy(time.Second).UpdateOnGet()

    // Create a basic config.
    cfg := gocache.NewConfig().
        WithMaxCapacity(1000).
        WithDefaultEvictionPolicy(ep)

    // Create a cache with that config.
    cache := gocache.New[string, int](cfg)

    // Set a value.
    cache.Set("foo", 3)

    // Get a value.
    fmt.Println(cache.Get("foo")) // 3

    // Wait for the value to expire.
    time.Sleep(time.Millisecond * 1001)

    // Get() returns zero value if not found in cache.
    fmt.Println(cache.Get("foo")) // 0

    // Check if cache has a value for a key.
    fmt.Println(cache.Has("foo")) // false
}

Contribute

Make a pull request.