go-cache Documentation

repository·master·Indexed 27 days ago

https://github.com/patrickmn/go-cache

An in-memory, thread-safe key:value store for Go applications running on a single machine. It provides expiration support and avoids network overhead by storing objects directly in memory. Features include default and custom expiration times, a cleanup interval for purging expired items, and the ability to persist and recover cache data using Items() and NewFrom().

Tokens
608
Snippets
3
Records
4
Agent score
44%

What's inside go-cache

  1. Persist and recover cache data

    master

    While go-cache is an in-memory store, you can save and load the entire cache to/from a file to recover from downtime.

    1. Use c.Items() to retrieve the underlying map[string]cache.Item for serialization.
    2. Use cache.NewFrom(items map[string]cache.Item) to create a new cache instance from a deserialized map.
  2. Set and Get values in the cache

    master

    Use c.Set(key string, value interface{}, expiration time.Duration) to store items and c.Get(key string) (interface{}, bool) to retrieve them.

    Expiration Options:

    • cache.DefaultExpiration: Uses the default expiration time defined when the cache was created.
    • cache.NoExpiration: The item will not expire until it is manually deleted or overwritten.

    Note on Type Assertion: Because c.Get returns an interface{}, you must use Go type assertion to convert the value back to its original type (e.g., foo.(string) or x.(*MyStruct)).

    import (
    	"fmt"
    	"github.com/patrickmn/go-cache"
    	"time"
    )
    
    func main() {
    	c := cache.New(5*time.Minute, 10*time.Minute)
    
    	// Set with default expiration
    	c.Set("foo", "bar", cache.DefaultExpiration)
    
    	// Set with no expiration
    	c.Set("baz", 42, cache.NoExpiration)
    
    	// Get value with type assertion
    	foo, found := c.Get("foo")
    	if found {
    		fmt.Println(foo.(string))
    	}
    }
  3. Initialize a new cache

    master

    Use cache.New(defaultExpiration time.Duration, cleanupInterval time.Duration) to create a new in-memory cache.

    • defaultExpiration: The amount of time that items should expire before being automatically purged.
    • cleanupInterval: The interval at which the cache should purge expired items.
    // Create a cache with a default expiration time of 5 minutes, and which
    // purges expired items every 10 minutes
    c := cache.New(5*time.Minute, 10*time.Minute)