cache

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2025 License: MIT Imports: 6 Imported by: 0

README

cache

Cache using Go 1.18 generics.

cache is an in-memory key:value store/cache similar to memcached that is suitable for applications running on a single machine.

import (
	"fmt"
	"github.com/alaingilbert/cache"
)

func main() {
	// Create a cache of "string" with a default expiration time of 5 minutes
	// and which purges expired items every 10 minutes (DefaultCleanupInterval)
	// The cleanup interval can be changed for a custom value using "CleanupInterval"
	// `cache.New[string](5*time.Minute, cache.CleanupInterval(time.Hour))`
	// The cleanup thread can be terminated using a context.Context
	// `cache.New[string](5*time.Minute, cache.WithContext(ctx))`
	c := cache.New[string](5*time.Minute)
	
	// Set the value of the key "key1" to "val1", with the default expiration time (5min)
	c.Set("key1", "val1")

	// Set the value of the key "key2" to "val2", with a 1sec expiration time
	c.Set("key2", "val2", cache.ExpireIn(time.Second))
	
	// Set the value of the key "key3" to "val3", which will expire on Jan 01 2100
	c.Set("key3", "val3", cache.ExpireAt(time.Date(2100, 1, 1, 0, 0, 0, 0, time.Local)))
	
	// Set the value of the key "key4" to "val4", with no expiration time
	// (the item won't be removed until it is re-set, or removed using
	// c.Delete("key4")
	c.Set("key4", "val4", cache.NoExpire)
	
	// Return either or not "key1" is in the cache and not expired
	found := c.Has("key1")

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

	// Delete "key1" from the cache
	c.Delete("key1")
	
	// Can also use a "Set" (data structure) for cache
	s := cache.NewSet[string](5*time.Minute)
	s.Set("key1")
	if s.Has("key1") {
		fmt.Println("found key1")
	}
	s.Delete("key1")
}

Documentation

Index

Constants

View Source
const (
	// NoExpiration ...
	NoExpiration time.Duration = -1
	// DefaultExpiration ...
	DefaultExpiration time.Duration = 0
)

Variables

View Source
var DefaultCleanupInterval = 10 * time.Minute

DefaultCleanupInterval is exported so that someone could override the value in their project

View Source
var ErrItemAlreadyExists = errors.New("item already exists")

ErrItemAlreadyExists ...

View Source
var ErrItemNotFound = errors.New("item does not exists")

ErrItemNotFound ...

Functions

func GetCast

func GetCast[T any, K comparable](c *Cache[K, any], k K) (value T, ok bool)

GetCast ...

func GetCastInto

func GetCastInto[T any, K comparable](c *Cache[K, any], k K, into *T) bool

GetCastInto ...

func GetTryCast

func GetTryCast[T any, K comparable](c *Cache[K, any], k K) (ok bool)

GetTryCast useful if you want to test if a key exists and is of a specific type `if GetTryCast[int](c, "someKey") {`

func NoExpire

func NoExpire(cfg *ItemConfig)

NoExpire ...

Types

type Cache

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

Cache ...

func New

func New[V any](defaultExpiration time.Duration, opts ...Option) *Cache[string, V]

New creates a cache with K as string

func NewWithKey

func NewWithKey[K comparable, V any](defaultExpiration time.Duration, opts ...Option) *Cache[K, V]

NewWithKey creates a cache with a custom comparable K provided by the user

func (*Cache[K, V]) Add

func (c *Cache[K, V]) Add(k K, v V, opts ...ItemOption) 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 (*Cache[K, V]) Delete

func (c *Cache[K, V]) Delete(k K)

Delete an item from the cache

func (*Cache[K, V]) DeleteAll

func (c *Cache[K, V]) DeleteAll()

DeleteAll deletes all items from the cache

func (*Cache[K, V]) DeleteExpired

func (c *Cache[K, V]) DeleteExpired()

DeleteExpired deletes all expired items from the cache

func (*Cache[K, V]) Destroy

func (c *Cache[K, V]) Destroy()

Destroy the cache object, cleanup all resources

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(k K) (value V, found bool)

Get a value associated to the given key

func (*Cache[K, V]) GetWithExpiration

func (c *Cache[K, V]) GetWithExpiration(k K) (value V, expiration time.Time, found bool)

GetWithExpiration gets a value and its expiration time from the cache. If the item never expires a zero value for time.Time is returned.

func (*Cache[K, V]) Has

func (c *Cache[K, V]) Has(k K) (found bool)

Has returns either or not the key is present in the cache

func (*Cache[K, V]) Items

func (c *Cache[K, V]) Items() map[K]Item[V]

Items copies all unexpired items in the cache into a new map and returns it.

func (*Cache[K, V]) Len

func (c *Cache[K, V]) Len() int

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

func (*Cache[K, V]) Replace

func (c *Cache[K, V]) Replace(k K, v V, opts ...ItemOption) error

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

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(k K, v V, opts ...ItemOption)

Set a key/value pair in the cache

func (*Cache[K, V]) Take

func (c *Cache[K, V]) Take(k K) (value V, found bool)

Take retrieve a value associated to the given key and delete the key from the cache

type Config

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

Config ...

func (*Config) CleanupInterval

func (c *Config) CleanupInterval(cleanupInterval time.Duration) *Config

CleanupInterval ...

func (*Config) WithClock

func (c *Config) WithClock(clock clockwork.Clock) *Config

WithClock ...

func (*Config) WithContext

func (c *Config) WithContext(ctx context.Context) *Config

WithContext ...

type Item

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

Item wrap the user provided value and add data to it

func (Item[V]) Expiration

func (i Item[V]) Expiration() time.Time

Expiration returns the expiration time

func (Item[V]) IsExpired

func (i Item[V]) IsExpired() bool

IsExpired returns either or not the item is expired right now

func (Item[V]) Value

func (i Item[V]) Value() V

Value returns the value contained by the item

type ItemConfig

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

ItemConfig ...

func (*ItemConfig) Duration

func (c *ItemConfig) Duration(d time.Duration) *ItemConfig

Duration ...

type ItemOption

type ItemOption func(cfg *ItemConfig)

ItemOption ...

func ExpireAt

func ExpireAt(t time.Time) ItemOption

ExpireAt ...

func ExpireIn

func ExpireIn(d time.Duration) ItemOption

ExpireIn can be used to override the default expiration for a key when calling the Add/Set/Replace methods

type Option

type Option func(cfg *Config)

Option ...

func CleanupInterval

func CleanupInterval(cleanupInterval time.Duration) Option

CleanupInterval changes the cleanup interval

func WithClock

func WithClock(clock clockwork.Clock) Option

WithClock changes the clock

func WithContext

func WithContext(ctx context.Context) Option

WithContext changes context

type SetCache

type SetCache[K comparable] struct {
	// contains filtered or unexported fields
}

SetCache ...

func NewSet

func NewSet[K comparable](defaultExpiration time.Duration, opts ...Option) *SetCache[K]

NewSet creates a new "set" cache

func (*SetCache[K]) Add

func (s *SetCache[K]) Add(k K, opts ...ItemOption) error

func (*SetCache[K]) Delete

func (s *SetCache[K]) Delete(k K)

func (*SetCache[K]) DeleteAll

func (s *SetCache[K]) DeleteAll()

func (*SetCache[K]) DeleteExpired

func (s *SetCache[K]) DeleteExpired()

func (*SetCache[K]) Destroy

func (s *SetCache[K]) Destroy()

func (*SetCache[K]) GetExpiration

func (s *SetCache[K]) GetExpiration(k K) (expiration time.Time, found bool)

func (*SetCache[K]) Has

func (s *SetCache[K]) Has(k K) bool

func (*SetCache[K]) Len

func (s *SetCache[K]) Len() int

func (*SetCache[K]) Replace

func (s *SetCache[K]) Replace(k K, opts ...ItemOption) error

func (*SetCache[K]) Set

func (s *SetCache[K]) Set(k K, opts ...ItemOption)

Directories

Path Synopsis
internal
mtx
Package mtx provides thread-safe wrappers for values and maps using read-write mutexes.
Package mtx provides thread-safe wrappers for values and maps using read-write mutexes.

Jump to

Keyboard shortcuts

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