memcache

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 11 Imported by: 0

README

memcache

Generic in-memory key-value cache.

codecov Go Reference

Documentation

Overview

Package memcache provides a generic in-memory key-value cache.

The capacity of a cache is the total number of keys it is allowed to hold.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidInterval = errors.New("provided interval must be greater than 0")
)

Functions

This section is empty.

Types

type Cache

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

Cache is a generic in-memory key-value cache.

func OpenAllKeysLFUCache added in v0.15.0

func OpenAllKeysLFUCache[K comparable, V any](capacity int, options ...Option[K, V]) (*Cache[K, V], error)

OpenAllKeysLFUCache opens a new in-memory key-value cache.

This policy evicts the least frequently used key when the cache would breach its capacity.

The capacity for this policy must be greater than 0.

Example
package main

import (
	"time"

	"github.com/wafer-bw/memcache"
)

func main() {
	capacity := 10
	interval := 1 * time.Second
	cache, err := memcache.OpenAllKeysLFUCache(capacity,
		memcache.WithActiveExpiration[int, string](interval),
		memcache.WithPassiveExpiration[int, string](),
	)
	if err != nil {
		panic(err)
	}
	defer cache.Close()
}
Output:

func OpenAllKeysLRUCache added in v0.13.0

func OpenAllKeysLRUCache[K comparable, V any](capacity int, options ...Option[K, V]) (*Cache[K, V], error)

OpenAllKeysLRUCache opens a new in-memory key-value cache.

This policy evicts the least recently used key when the cache would breach its capacity.

The capacity for this policy must be greater than 0.

Example
package main

import (
	"time"

	"github.com/wafer-bw/memcache"
)

func main() {
	capacity := 10
	interval := 1 * time.Second
	cache, err := memcache.OpenAllKeysLRUCache(capacity,
		memcache.WithActiveExpiration[int, string](interval),
		memcache.WithPassiveExpiration[int, string](),
	)
	if err != nil {
		panic(err)
	}
	defer cache.Close()
}
Output:

func OpenNoEvictionCache added in v0.11.0

func OpenNoEvictionCache[K comparable, V any](options ...Option[K, V]) (*Cache[K, V], error)

OpenNoEvictionCache opens a new in-memory key-value cache.

This policy will ignore any additional keys that would cause the cache to breach its capacity.

The capacity for this policy must be 0 (default) or set to a greater value via WithCapacity.

Example
package main

import (
	"time"

	"github.com/wafer-bw/memcache"
)

func main() {
	capacity := 10
	interval := 1 * time.Second
	cache, err := memcache.OpenNoEvictionCache(
		memcache.WithActiveExpiration[int, string](interval),
		memcache.WithPassiveExpiration[int, string](),
		memcache.WithCapacity[int, string](capacity),
	)
	if err != nil {
		panic(err)
	}
	defer cache.Close()
}
Output:

func OpenVolatileLRUCache added in v0.13.0

func OpenVolatileLRUCache[K comparable, V any](capacity int, options ...Option[K, V]) (*Cache[K, V], error)

OpenVolatileLRUCache opens a new in-memory key-value cache.

This policy evicts the least recently used key with a ttl when the cache would breach its capacity. If no keys have a ttl, then the least recently used key is evicted.

The capacity for this policy must be greater than 0.

Example
package main

import (
	"time"

	"github.com/wafer-bw/memcache"
)

func main() {
	capacity := 10
	interval := 1 * time.Second
	cache, err := memcache.OpenVolatileLRUCache(capacity,
		memcache.WithActiveExpiration[int, string](interval),
		memcache.WithPassiveExpiration[int, string](),
	)
	if err != nil {
		panic(err)
	}
	defer cache.Close()
}
Output:

func (*Cache[K, V]) Close added in v0.5.0

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

Close the cache, stopping all running goroutines. Should be called when the cache is no longer needed.

func (*Cache[K, V]) Delete

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

Delete provided keys from the cache.

Example
package main

import (
	"fmt"

	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}
	cache.Set(1, "one")
	cache.Set(2, "two")
	cache.Set(3, "three")

	cache.Delete(1)
	cache.Delete(2, 3)

	_, ok := cache.Get(1)
	fmt.Println(ok)
	_, ok = cache.Get(2)
	fmt.Println(ok)
	_, ok = cache.Get(3)
	fmt.Println(ok)
}
Output:

false
false
false

func (*Cache[K, V]) Flush

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

Flush the cache, deleting all keys.

Example
package main

import (
	"fmt"

	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}

	cache.Set(1, "one")
	cache.Set(2, "two")

	cache.Flush()

	_, ok := cache.Get(1)
	fmt.Println(ok)

	_, ok = cache.Get(2)
	fmt.Println(ok)
}
Output:

false
false

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(key K) (V, bool)

Get returns the value associated with the provided key if it exists, or false if it does not.

If the cache was opened with WithPassiveExpiration and the requested key is expired, it will be deleted from the cache and false will be returned.

Example
package main

import (
	"fmt"

	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}

	cache.Set(1, "one")

	v, ok := cache.Get(1)
	fmt.Println(v)
	fmt.Println(ok)
	_, ok = cache.Get(2)
	fmt.Println(ok)
}
Output:

one
true
false

func (*Cache[K, V]) Keys

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

Keys returns a slice of all keys currently in the cache.

Example
package main

import (
	"fmt"

	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}

	cache.Set(1, "one")
	cache.Set(2, "two")

	for _, key := range cache.Keys() {
		fmt.Println(key)
	}
}
Output:

1
2

func (*Cache[K, V]) RandomKey added in v0.14.0

func (c *Cache[K, V]) RandomKey() (K, bool)

RandomKey returns a random key from the cache, or false if the cache is empty.

Example
package main

import (
	"fmt"

	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}

	cache.Set(1, "one")
	cache.Set(2, "two")

	key, ok := cache.RandomKey()
	_ = key
	fmt.Println(ok)
}
Output:

true

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(key K, value V)

Set non-expiring key to value in the cache.

Example
package main

import (
	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}

	cache.Set(1, "one")
}
Output:

func (*Cache[K, V]) SetEx added in v0.4.0

func (c *Cache[K, V]) SetEx(key K, value V, ttl time.Duration)

SetEx key that will expire after ttl to value in the cache.

Example
package main

import (
	"time"

	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}

	cache.SetEx(1, "one", 1*time.Second)
}
Output:

func (*Cache[K, V]) Size added in v0.3.0

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

Size returns the number of items currently in the cache.

Example
package main

import (
	"fmt"

	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}

	cache.Set(1, "one")
	cache.Set(2, "two")

	fmt.Println(cache.Size())
}
Output:

2

func (*Cache[K, V]) TTL added in v0.12.0

func (c *Cache[K, V]) TTL(key K) (*time.Duration, bool)

TTL for the provided key if it exists, or false if it does not. If the key is will not expire then (nil, true) will be returned.

Example
package main

import (
	"fmt"
	"time"

	"github.com/wafer-bw/memcache"
)

func main() {
	cache, err := memcache.OpenNoEvictionCache[int, string]()
	if err != nil {
		panic(err)
	}

	cache.SetEx(1, "one", 2*time.Minute)

	v, ok := cache.TTL(1)
	fmt.Println(v.Truncate(time.Minute))
	fmt.Println(ok)
}
Output:

1m0s
true

type InvalidCapacityError added in v0.11.2

type InvalidCapacityError struct {
	Capacity int
	Minimum  int
	Policy   string
}

func (InvalidCapacityError) Error added in v0.11.2

func (e InvalidCapacityError) Error() string

type Option added in v0.4.0

type Option[K comparable, V any] func(*Cache[K, V]) error

Option functions can be passed to open functions like OpenNoEvictionCache to control optional properties of the returned Cache.

func WithActiveExpiration added in v0.6.0

func WithActiveExpiration[K comparable, V any](interval time.Duration) Option[K, V]

WithActiveExpiration enables the active deletion of all expired keys at the provided interval.

This comes with a minor performance cost as every tick requires a read lock to collect all expired keys followed by a write lock to delete them.

func WithCapacity added in v0.11.0

func WithCapacity[K comparable, V any](capacity int) Option[K, V]

WithCapacity sets the maximum number of keys that the cache can hold.

This option is made available to set the capacity of policies that do not need or use a capacity by default.

func WithPassiveExpiration added in v0.2.0

func WithPassiveExpiration[K comparable, V any]() Option[K, V]

WithPassiveExpiration enables the passive deletion of expired keys if they are found to be expired when accessed by Cache.Get.

This comes with a minor performance cost as Cache.Get now must acquire a write lock instead of a read lock.

Directories

Path Synopsis
internal
mocks/mockexpire
Package mockexpire is a generated GoMock package.
Package mockexpire is a generated GoMock package.
ports
Package ports provides commonly shared internal interfaces.
Package ports provides commonly shared internal interfaces.
substore/randxs
Package randxs provides a thread-safe store for random access to keys.
Package randxs provides a thread-safe store for random access to keys.

Jump to

Keyboard shortcuts

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