Skip to content
/ cache Public
generated from atomicgo/template

🧠 A generic, thread-safe cache implementation in Go for improved performance!

License

Notifications You must be signed in to change notification settings

atomicgo/cache

Repository files navigation

AtomicGo | cache

Downloads Latest Release Tests Coverage Unit test count License: MIT Go report


Documentation | Contributing | Code of Conduct


AtomicGo

go get atomicgo.dev/cache

cache

import "atomicgo.dev/cache"

Package cache is a generic, fast and thread-safe cache implementation to improve performance of your Go applications.

Index

type Cache

Cache is a fast and thread-safe cache implementation with expiration.

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

func New

func New[T any](options ...Options) *Cache[T]

New returns a new Cache. The default Expiration time is 0, which means no Expiration.

Example

package main

import (
	"atomicgo.dev/cache"
	"time"
)

func main() {
	// Create a cache for string values, without any options.
	cache.New[string]()

	// Create a cache for string values, with options.
	cache.New[string](cache.Options{
		DefaultExpiration: time.Second * 10,
	})

	// Create a cache for int values, without any options.
	cache.New[int]()

	// Create a cache for int values, with options.
	cache.New[int](cache.Options{
		DefaultExpiration: time.Second * 10,
	})

	// Create a cache for any values, without any options.
	cache.New[any]()

	// Create a cache for any values, with options.
	cache.New[any](cache.Options{
		DefaultExpiration: time.Second * 10,
	})
}

func (*Cache[T]) Close

func (c *Cache[T]) Close()

Close purges the cache and stops the auto purge goroutine, if active.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")

	// Close the cache.
	c.Close()

	// Get the size.
	fmt.Println(c.Size())

}

Output

0

func (*Cache[T]) Contains

func (c *Cache[T]) Contains(key string) bool

Contains returns true if the key is in the cache, and the key is not expired.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")

	// Check if the cache contains a key.
	fmt.Println(c.Contains("1"))
	fmt.Println(c.Contains("4"))

}

Output

true
false

func (*Cache[T]) Delete

func (c *Cache[T]) Delete(key string)

Delete removes the key from the cache.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")

	// Delete a key.
	c.Delete("3")

	// Get the size.
	fmt.Println(c.Size())

}

Output

2

func (*Cache[T]) EnableAutoPurge

func (c *Cache[T]) EnableAutoPurge(purgeInterval ...time.Duration) *Cache[T]

EnableAutoPurge starts a goroutine that purges expired keys from the cache. The interval is the time between purges. If the interval is 0, the default interval of the cache options is used. If the cache options do not specify a default interval, the default interval is 1 minute.

func (*Cache[T]) Expired

func (c *Cache[T]) Expired(key string) bool

Expired returns true if the key is expired.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string](cache.Options{
		DefaultExpiration: time.Millisecond * 10,
	})

	// Set a value for a key.
	c.Set("1", "one")

	// Check if the key is expired.
	fmt.Println(c.Expired("1"))

	// Sleep for 10ms to let the key expire.
	time.Sleep(time.Millisecond * 10)

	// Check if the key is expired.
	fmt.Println(c.Expired("1"))

}

Output

false
true

func (*Cache[T]) Get

func (c *Cache[T]) Get(key string) T

Get returns the value for a key. If the key does not exist, nil is returned. If the key is expired, the zero value is returned and the key is deleted.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
)

func main() {
	c := cache.New[string]()

	// Set a value for a key.
	c.Set("1", "one")

	// Get the value for a key.
	fmt.Println(c.Get("1"))

}

Output

one

func (*Cache[T]) GetEntry

func (c *Cache[T]) GetEntry(key string) *Entry[T]

GetEntry returns the Entry for a key. If the key does not exist, nil is returned.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string](cache.Options{
		DefaultExpiration: time.Second * 10,
	})

	// Set a value for a key.
	c.Set("1", "one")

	// Get the entry for a key.
	entry := c.GetEntry("1")
	fmt.Println(entry.Value)
	fmt.Println(entry.Expiration)

}

Output

one
10s

func (*Cache[T]) GetExpiration

func (c *Cache[T]) GetExpiration(key string) time.Duration

GetExpiration returns the Expiration time for a key.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string](cache.Options{
		DefaultExpiration: time.Second * 10,
	})

	// Set a value for a key.
	c.Set("1", "one")

	// Get the expiration for a key.
	fmt.Println(c.GetExpiration("1"))

}

Output

10s

func (*Cache[T]) GetOrSet

func (c *Cache[T]) GetOrSet(key string, callback func() T, expiration ...time.Duration) T

GetOrSet returns the value for a key. If the key does not exist, the value is set to the result of the callback function and returned. If the key is expired, the value is set to the result of the callback function and returned.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
)

func main() {
	c := cache.New[string]()

	// Try to get or set a value for a key.
	c.GetOrSet("1", func() string {
		return "one"
	})

	fmt.Println(c.Get("1"))

	// try to get or set a value for an existing key.
	c.GetOrSet("1", func() string {
		return "something else"
	})
	fmt.Println(c.Get("1"))

	// delete the key
	c.Delete("1")

	// try to get or set a value for a non-existing key.
	c.GetOrSet("1", func() string {
		return "something else"
	})
	fmt.Println(c.Get("1"))

}

Output

one
one
something else

func (*Cache[T]) Keys

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

Keys returns a slice of all keys in the cache, expired or not.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"sort"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")

	// Get the keys.
	keys := c.Keys()
	sort.Strings(keys)

	fmt.Println(keys)

}

Output

[1 2 3]

func (*Cache[T]) Purge

func (c *Cache[T]) Purge()

Purge removes all keys from the cache.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")

	// Purge the cache.
	c.Purge()

	// Check if the cache is empty.
	fmt.Println(c.Size())

}

Output

0

func (*Cache[T]) PurgeExpired

func (c *Cache[T]) PurgeExpired()

PurgeExpired removes all expired keys from the cache.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string](cache.Options{
		DefaultExpiration: time.Second,
	})

	// Fill the cache with some values.
	c.Set("1", "one", time.Millisecond*10)
	c.Set("2", "two", time.Millisecond*10)
	c.Set("3", "three")

	// Purge the expired keys.
	c.PurgeExpired()
	fmt.Println(c.Size())

	// Sleep for 10ms to let the first two keys expire.
	time.Sleep(time.Millisecond * 10)

	// Purge the expired keys.
	c.PurgeExpired()
	fmt.Println(c.Size())

}

Output

3
1

func (*Cache[T]) Set

func (c *Cache[T]) Set(key string, value T, expiration ...time.Duration)

Set sets the value for a key. If the key already exists, the value is overwritten. If the Expiration time is 0, the default Expiration time is used.

Example

package main

import (
	"atomicgo.dev/cache"
	"time"
)

func main() {
	c := cache.New[string]()

	// Set a value for a key.
	c.Set("1", "one")

	// Set a value for a key with a custom expiration.
	c.Set("2", "two", time.Second*10)
}

func (*Cache[T]) SetExpiration

func (c *Cache[T]) SetExpiration(expiration time.Duration)

SetExpiration sets the Expiration time all keys in the cache.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string](cache.Options{
		DefaultExpiration: time.Second * 10,
	})

	// Set a value for a key.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three", time.Second*1337)

	// Set the expiration for a key.
	c.SetExpiration(time.Second * 20)

	// Get the expiration for a key.
	fmt.Println(c.GetExpiration("1"))
	fmt.Println(c.GetExpiration("2"))
	fmt.Println(c.GetExpiration("3"))

}

Output

20s
20s
20s

func (*Cache[T]) Size

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

Size returns the number of keys in the cache, expired or not.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")

	// Get the size.
	fmt.Println(c.Size())

}

Output

3

func (*Cache[T]) StopAutoPurge

func (c *Cache[T]) StopAutoPurge()

StopAutoPurge stops the auto purge goroutine.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string](cache.Options{
		AutoPurgeInterval: time.Millisecond * 10,
	})
	c.EnableAutoPurge()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")

	// Stop the auto purge.
	c.StopAutoPurge()

	// Sleep for 10 milliseconds to let the auto purge run.
	time.Sleep(time.Millisecond * 10)

	// Get the size.
	fmt.Println(c.Size())

}

Output

3

func (*Cache[T]) ValidKeys

func (c *Cache[T]) ValidKeys() []string

ValidKeys returns a slice of all valid keys in the cache.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"sort"
	"time"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")
	c.Set("expiresSoon", "data", time.Millisecond*10)

	validKeys := c.ValidKeys()
	sort.Strings(validKeys)

	fmt.Println(validKeys)

	// Sleep for 10ms to let the "expiresSoon" key expire.
	time.Sleep(time.Millisecond * 10)

	// Get the valid keys.
	validKeys = c.ValidKeys()
	sort.Strings(validKeys)
	fmt.Println(validKeys)

}

Output

[1 2 3 expiresSoon]
[1 2 3]

func (*Cache[T]) ValidSize

func (c *Cache[T]) ValidSize() int

ValidSize returns the number of keys in the cache that are not expired.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")
	c.Set("expiresSoon", "data", time.Millisecond*10)

	fmt.Println(c.ValidSize())

	// Sleep for 10ms to let the "expiresSoon" key expire.
	time.Sleep(time.Millisecond * 10)

	// Get the valid size.
	fmt.Println(c.ValidSize())

}

Output

4
3

func (*Cache[T]) Values

func (c *Cache[T]) Values() []T

Values returns a slice of all values in the cache.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"sort"
)

func main() {
	c := cache.New[string]()

	// Fill the cache with some values.
	c.Set("1", "one")
	c.Set("2", "two")
	c.Set("3", "three")

	// Get the values.
	values := c.Values()
	sort.Strings(values)

	fmt.Println(values)

}

Output

[one three two]

type Entry

Entry is a cache entry.

type Entry[T any] struct {
    Value      T
    CachedAt   time.Time
    Expiration time.Duration
}

func (Entry[T]) Expired

func (e Entry[T]) Expired() bool

Expired returns if the Entry is expired.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string](cache.Options{
		DefaultExpiration: time.Millisecond * 10,
	})

	// Set a value for a key.
	c.Set("1", "one")

	// Get the entry for a key.
	entry := c.GetEntry("1")

	// Check if the entry is expired.
	fmt.Println(entry.Expired())

	// Sleep for 10ms to let the entry expire.
	time.Sleep(time.Millisecond * 10)

	// Check if the entry is expired.
	fmt.Println(entry.Expired())

}

Output

false
true

func (*Entry[T]) SetExpiration

func (e *Entry[T]) SetExpiration(expiration time.Duration)

SetExpiration sets the Expiration time for the Entry.

Example

package main

import (
	"atomicgo.dev/cache"
	"fmt"
	"time"
)

func main() {
	c := cache.New[string](cache.Options{
		DefaultExpiration: time.Second * 10,
	})

	// Set a value for a key.
	c.Set("1", "one")

	// Get the entry for a key.
	entry := c.GetEntry("1")

	// Set the expiration for the entry.
	entry.SetExpiration(time.Second * 20)

	// Get the expiration for a key.
	fmt.Println(c.GetExpiration("1"))

}

Output

20s

type Options

Options can be passed to New to configure the cache.

type Options struct {
    DefaultExpiration time.Duration
    AutoPurgeInterval time.Duration
}

Generated by gomarkdoc


AtomicGo.dev  ·  with ❤️ by @MarvinJWendt | MarvinJWendt.com

About

🧠 A generic, thread-safe cache implementation in Go for improved performance!

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Languages