cache

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2022 License: MPL-2.0 Imports: 3 Imported by: 0

README

go-cache

GoDoc

A generic cache in Go

A basic generic timed in-memory cache implementation supporting any comparable key type and any value type.

Usage

A basic usage example:

package main

import (
	"fmt"
	"time"

	"github.com/antichris/go-cache"
)

func main() {
	// Initialize a new cache with string keys for string values.
	c := cache.New[string, string](10 * time.Millisecond)

	// Since the cache checks expiration timers in an asynchronous loop
	// always shut it down after use to avoid resource leaks.
	defer c.Shutdown()

	// A closure to output results of `Get` attempts for this demo.
	show := func(k string) {
		v, ok := c.Get(k)
		fmt.Printf("key: %q, value: %q, present: %v\n", k, v, ok)
	}

	// Try with a value that is absent from the cache.
	show("foo")

	c.Put("bar", "baz")
	// Try with the value that we just put in the cache.
	show("bar")

	// Wait a bit past the expiration time.
	time.Sleep(15 * time.Millisecond)

	// Try with the value that should be expired by now.
	show("bar")

	// Output:
	// key: "foo", value: "", present: false
	// key: "bar", value: "baz", present: true
	// key: "bar", value: "", present: false
}

Installation

go get github.com/antichris/go-cache

License

The source code of this project is released under Mozilla Public License Version 2.0. See LICENSE.

Documentation

Overview

Package cache implements a generic timed key-value in-memory data store.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

Cache of values.

func New

func New[K comparable, V any](defaultTTL time.Duration) *Cache[K, V]

New Cache instance.

Example
// Initialize a new cache with string keys for string values.
c := cache.New[string, string](10 * time.Millisecond)

// Since the cache checks expiration timers in an asynchronous loop
// always shut it down after use to avoid resource leaks.
defer c.Shutdown()

// A closure to output results of `Get` attempts for this demo.
show := func(k string) {
	v, ok := c.Get(k)
	fmt.Printf("key: %q, value: %q, present: %v\n", k, v, ok)
}

// Try with a value that is absent from the cache.
show("foo")

c.Put("bar", "baz")
// Try with the value that we just put in the cache.
show("bar")

// Wait a bit past the expiration time.
time.Sleep(15 * time.Millisecond)

// Try with the value that should be expired by now.
show("bar")
Output:

key: "foo", value: "", present: false
key: "bar", value: "baz", present: true
key: "bar", value: "", present: false

func NewByOf

func NewByOf[K comparable, V any](
	defaultTTL time.Duration,
	sampleKey K,
	sampleValue V,
) *Cache[K, V]

NewByOf returns a new cache for values of the same type as sampleValue, indexed by keys of the same type as sampleKey.

Example
type user struct {
	id    uint
	email string
}

// A sample value.
u := user{}

// Here the cache value type is `user`, and the key type is the type
// of its `id` field. This lets you change either of those types
// without the need to touch this cache initialization.
c := cache.NewByOf(10*time.Millisecond, u.id, u)

// Since the cache checks expiration timers in an asynchronous loop
// always shut it down after use to avoid resource leaks.
defer c.Shutdown()

const ID = 1

c.Put(ID, user{
	id:    ID,
	email: "alice@example.com",
})

v, _ := c.Get(ID)
fmt.Printf("email: %s", v.email)
Output:

email: alice@example.com

func (*Cache[K, V]) Drop

func (c *Cache[K, V]) Drop(key K) (value V, ok bool)

Drop cached item and return its last value.

func (*Cache[K, V]) Get

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

Get cached item.

Since the cache can hold concrete value types, the second return parameter indicates whether the value was actually found in cache.

func (*Cache[K, V]) GetOrPut

func (c *Cache[K, V]) GetOrPut(
	key K,
	provider Getter[K, V],
) (value V, ok bool)

GetOrPut returns the value in cache at the given key, or, if absent, the one returned by provider, after having put it in the cache with the cache-default time-to-live.

Example
type user struct {
	id    uint8
	email string
}

// A sample value.
u := user{}

// Here the cache value type is `user`, and the key type is the type
// of its `id` field. This lets you change either of those types
// without the need to touch this cache initialization.
c := cache.NewByOf(10*time.Millisecond, u.id, u)

// Since the cache checks expiration timers in an asynchronous loop
// always shut it down after use to avoid resource leaks.
defer c.Shutdown()

getBob := func(id uint8) (user, bool) {
	// We return a hard-coded value for this example, although there
	// could be a call to another, more permanent storage here.
	return user{
		id:    id,
		email: "bob@example.com",
	}, true
}
bob, _ := c.GetOrPut(1, cache.GetterFunc[uint8, user](getBob))

fmt.Printf("email: %s", bob.email)
Output:

email: bob@example.com

func (*Cache[K, V]) GetOrPutWithTTL

func (c *Cache[K, V]) GetOrPutWithTTL(
	key K,
	provider Getter[K, V],
	ttl time.Duration,
) (value V, ok bool)

GetOrPutWithTTL returns the value in cache at the given key, or, if absent, the one returned by provider, after having put it in the cache with the given time-to-live.

func (*Cache[K, T]) Has

func (c *Cache[K, T]) Has(key K) bool

Has returns whether an item for given key is present in the cache.

Unlike Touch, this does not extend the lifetime of the item.

func (*Cache[K, V]) IsShutDown

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

IsShutDown returns whether item expiry timer processing is terminated.

func (*Cache[K, V]) Length

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

Lenght of cache is the number of items currently in the cache.

func (*Cache[K, V]) Put

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

Put a value in cache at the given key, with the cache-default time-to-live.

func (*Cache[K, V]) PutWithTTL

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

PutWithTTL puts a value in cache at the given key, with the given time-to-live.

func (*Cache[K, V]) Shutdown

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

Shutdown terminates the goroutine processing item expiry timers.

func (*Cache[K, T]) Touch

func (c *Cache[K, T]) Touch(key K) bool

Touch a cached value, if present, to extend its lifetime. Returns false if the key has not been found in the cache.

type Getter

type Getter[K comparable, V any] interface {
	// Get value for given key and return if that was successful.
	Get(key K) (value V, ok bool)
}

A Getter can get a value for a key.

type GetterFunc

type GetterFunc[K comparable, V any] func(key K) (value V, ok bool)

GetterFunc is a func that implements the Getter interface.

func (GetterFunc[K, V]) Get

func (f GetterFunc[K, V]) Get(key K) (value V, ok bool)

type SimpleGetterFunc

type SimpleGetterFunc[K comparable, V any] func() (value V)

SimpleGetterFunc is the simplest func implementing Getter, that always returns a value.

func (SimpleGetterFunc[K, V]) Get

func (f SimpleGetterFunc[K, V]) Get(key K) (value V, ok bool)

Jump to

Keyboard shortcuts

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