cache

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2022 License: MIT Imports: 8 Imported by: 2

README

go-cache

go-cache is an in-memory key:value store/cache similar to memcached that is suitable for applications running on a single machine. Its major advantage is that, being essentially a thread-safe map[string]interface{} with expiration times, it doesn't need to serialize or transmit its contents over the network.

Any object can be stored, for a given duration or forever, and the cache can be safely used by multiple goroutines.

Although go-cache isn't meant to be used as a persistent datastore, the entire cache can be saved to and loaded from a file (using c.Items() to retrieve the items map to serialize, and NewFrom() to create a cache from a deserialized one) to recover from downtime quickly. (See the docs for NewFrom() for caveats.)

Installation

go get github.com/patrickmn/go-cache

Usage
import (
	"fmt"
	"github.com/patrickmn/go-cache"
	"time"
)

func main() {
	// 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)

	// Set the value of the key "foo" to "bar", with the default expiration time
	c.Set("foo", "bar", cache.DefaultExpiration)

	// Set the value of the key "baz" to 42, with no expiration time
	// (the item won't be removed until it is re-set, or removed using
	// c.Delete("baz")
	c.Set("baz", 42, cache.NoExpiration)

	// Get the string associated with the key "foo" from the cache
	foo, found := c.Get("foo")
	if found {
		fmt.Println(foo)
	}

	// Since Go is statically typed, and cache values can be anything, type
	// assertion is needed when values are being passed to functions that don't
	// take arbitrary types, (i.e. interface{}). The simplest way to do this for
	// values which will only be used once--e.g. for passing to another
	// function--is:
	foo, found := c.Get("foo")
	if found {
		MyFunction(foo.(string))
	}

	// This gets tedious if the value is used several times in the same function.
	// You might do either of the following instead:
	if x, found := c.Get("foo"); found {
		foo := x.(string)
		// ...
	}
	// or
	var foo string
	if x, found := c.Get("foo"); found {
		foo = x.(string)
	}
	// ...
	// foo can then be passed around freely as a string

	// Want performance? Store pointers!
	c.Set("foo", &MyStruct, cache.DefaultExpiration)
	if x, found := c.Get("foo"); found {
		foo := x.(*MyStruct)
			// ...
	}
}
Reference

godoc or http://godoc.org/github.com/patrickmn/go-cache

Documentation

Index

Constants

View Source
const (
	// For use with functions that take an expiration time.
	NoExpiration time.Duration = -1
	// For use with functions that take an expiration time. Equivalent to
	// passing in the same expiration duration as was given to newMutexCache() or
	// newMutexCacheFrom() when the cache was created (e.g. 5 minutes.)
	DefaultExpiration time.Duration = 0
)

Variables

This section is empty.

Functions

func Seed

func Seed() uint32

Types

type Cache

type Cache interface {
	Set(k string, x interface{}, d time.Duration)
	Add(k string, x interface{}, d time.Duration) error
	Replace(k string, x interface{}, d time.Duration) error
	Get(k string) (interface{}, bool)
	GetWithExpiration(k string) (interface{}, time.Time, bool)
	IncrementInt(k string, n int64) (interface{}, error)
	IncrementFloat(k string, n float64) (interface{}, error)
	DecrementInt(k string, n int64) (interface{}, error)
	DecrementFloat(k string, n float64) (interface{}, error)
	Delete(k string)
	DeleteExpired()
	Items() map[string]Item
	ItemCount() int
	Flush()
}

func New

func New(opts ...Option) Cache

type DJB33Hasher

type DJB33Hasher struct {
	Seed uint32
}

func (*DJB33Hasher) Sum32

func (hasher *DJB33Hasher) Sum32(k string) uint32

type Hash32

type Hash32 interface {
	Sum32(k string) uint32
}

type Item

type Item struct {
	Object     interface{}
	Expiration int64
}

func (Item) Expired

func (item Item) Expired() bool

Returns true if the item has expired.

type MutexCache

type MutexCache struct {
	// contains filtered or unexported fields
}

func (MutexCache) Add

func (c MutexCache) Add(k string, x interface{}, d time.Duration) error

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. Returns an error otherwise.

func (MutexCache) DecrementFloat

func (c MutexCache) DecrementFloat(k string, n float64) (interface{}, error)

DecrementInt an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to decrement it by n. Pass a negative number to decrement the value. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementFloat64.

func (MutexCache) DecrementInt

func (c MutexCache) DecrementInt(k string, n int64) (interface{}, error)

DecrementInt an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to decrement it by n. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementInt64.

func (MutexCache) Delete

func (c MutexCache) Delete(k string)

Delete an item from the cache. Does nothing if the key is not in the cache.

func (MutexCache) DeleteExpired

func (c MutexCache) DeleteExpired()

Delete all expired items from the cache.

func (MutexCache) Flush

func (c MutexCache) Flush()

Delete all items from the cache.

func (MutexCache) Get

func (c MutexCache) Get(k string) (interface{}, bool)

Get an item from the cache. Returns the item or nil, and a bool indicating whether the key was found.

func (MutexCache) GetWithExpiration

func (c MutexCache) GetWithExpiration(k string) (interface{}, time.Time, bool)

GetWithExpiration returns an item and its expiration time from the cache. It returns the item or nil, the expiration time if one is set (if the item never expires a zero value for time.Time is returned), and a bool indicating whether the key was found.

func (MutexCache) IncrementFloat

func (c MutexCache) IncrementFloat(k string, n float64) (interface{}, error)

IncrementInt an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to increment it by n. Pass a negative number to decrement the value. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementFloat64.

func (MutexCache) IncrementInt

func (c MutexCache) IncrementInt(k string, n int64) (interface{}, error)

IncrementInt an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to increment it by n. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementInt64.

func (MutexCache) ItemCount

func (c MutexCache) ItemCount() int

Returns the number of items in the cache. This may include items that have expired, but have not yet been cleaned up.

func (MutexCache) Items

func (c MutexCache) Items() map[string]Item

Copies all unexpired items in the cache into a newMutexCache map and returns it.

func (MutexCache) Replace

func (c MutexCache) Replace(k string, x interface{}, d time.Duration) error

Set a newMutexCache value for the cache key only if it already exists, and the existing item hasn't expired. Returns an error otherwise.

func (MutexCache) Set

func (c MutexCache) Set(k string, x interface{}, d time.Duration)

Add an item to the cache, replacing any existing item. If the duration is 0 (DefaultExpiration), the cache's default expiration time is used. If it is -1 (NoExpiration), the item never expires.

type Option

type Option func(o *options)

func CleanupInterval

func CleanupInterval(interval time.Duration) Option

func ExpirationTime

func ExpirationTime(expiration time.Duration) Option

func Hasher

func Hasher(hasher Hash32) Option

func OnEvicted

func OnEvicted(onEvicted func(string, interface{})) Option

func Shards

func Shards(shards int) Option

type ShardedCache

type ShardedCache struct {
	// contains filtered or unexported fields
}

func (ShardedCache) Add

func (sc ShardedCache) Add(k string, x interface{}, d time.Duration) error

func (ShardedCache) DecrementFloat

func (sc ShardedCache) DecrementFloat(k string, n float64) (interface{}, error)

func (ShardedCache) DecrementInt

func (sc ShardedCache) DecrementInt(k string, n int64) (interface{}, error)

func (ShardedCache) Delete

func (sc ShardedCache) Delete(k string)

func (ShardedCache) DeleteExpired

func (sc ShardedCache) DeleteExpired()

func (ShardedCache) Flush

func (sc ShardedCache) Flush()

func (ShardedCache) Get

func (sc ShardedCache) Get(k string) (interface{}, bool)

func (ShardedCache) GetWithExpiration

func (sc ShardedCache) GetWithExpiration(k string) (interface{}, time.Time, bool)

func (ShardedCache) IncrementFloat

func (sc ShardedCache) IncrementFloat(k string, n float64) (interface{}, error)

func (ShardedCache) IncrementInt

func (sc ShardedCache) IncrementInt(k string, n int64) (interface{}, error)

func (ShardedCache) ItemCount

func (sc ShardedCache) ItemCount() int

func (ShardedCache) Items

func (sc ShardedCache) Items() map[string]Item

func (ShardedCache) Replace

func (sc ShardedCache) Replace(k string, x interface{}, d time.Duration) error

func (ShardedCache) Set

func (sc ShardedCache) Set(k string, x interface{}, d time.Duration)

Jump to

Keyboard shortcuts

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