ttlcache

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2020 License: MIT Imports: 3 Imported by: 0

README

TTLCache - an in-memory cache with expiration

TTLCache is a simple key/value cache in golang with the following functions:

  1. Thread-safe
  2. Individual expiring time or global expiring time, you can choose
  3. Auto-Extending expiration on Get -or- DNS style TTL, see SkipTtlExtensionOnHit(bool)
  4. Fast and memory efficient
  5. Can trigger callback on key expiration
  6. Cleanup resources by calling Close() at end of lifecycle.

Note (issue #25): by default, due to historic reasons, the TTL will be reset on each cache hit and you need to explicitly configure the cache to use a TTL that will not get extended.

Build Status

Usage
import (
  "time"
  "fmt"

  "github.com/ReneKroon/ttlcache"
)

func main () {
  newItemCallback := func(key string, value interface{}) {
		fmt.Printf("New key(%s) added\n", key)
  }
  checkExpirationCallback := func(key string, value interface{}) bool {
		if key == "key1" {
		    // if the key equals "key1", the value
		    // will not be allowed to expire
		    return false
		}
		// all other values are allowed to expire
		return true
	}
  expirationCallback := func(key string, value interface{}) {
		fmt.Printf("This key(%s) has expired\n", key)
	}

  cache := ttlcache.NewCache()
  defer cache.Close()
  cache.SetTTL(time.Duration(10 * time.Second))
  cache.SetExpirationCallback(expirationCallback)

  cache.Set("key", "value")
  cache.SetWithTTL("keyWithTTL", "value", 10 * time.Second)

  value, exists := cache.Get("key")
  count := cache.Count()
  result := cache.Remove("key")
}
TTLCache - Some design considerations
  1. The complexity of the current cache is already quite high. Therefore i will not add 'convenience' features like an interface to supply a function to get missing keys.
  2. The locking should be done only in the functions of the Cache struct. Else data races can occur or recursive locks are needed, which are both unwanted.
  3. I prefer correct functionality over fast tests. It's ok for new tests to take seconds to proof something.
Original Project

TTLCache was forked from wunderlist/ttlcache to add extra functions not avaiable in the original scope. The main differences are:

  1. A item can store any kind of object, previously, only strings could be saved
  2. Optionally, you can add callbacks too: check if a value should expire, be notified if a value expires, and be notified when new values are added to the cache
  3. The expiration can be either global or per item
  4. Can exist items without expiration time
  5. Expirations and callbacks are realtime. Don't have a pooling time to check anymore, now it's done with a heap.

Documentation

Index

Constants

View Source
const (
	// ItemNotExpire Will avoid the item being expired by TTL, but can still be exired by callback etc.
	ItemNotExpire time.Duration = -1
	// ItemExpireWithGlobalTTL will use the global TTL when set.
	ItemExpireWithGlobalTTL time.Duration = 0
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

Cache is a synchronized map of items that can auto-expire once stale

func NewCache

func NewCache() *Cache

NewCache is a helper to create instance of the Cache struct

func (*Cache) Close added in v1.6.1

func (cache *Cache) Close()

Close calls Purge, and then stops the goroutine that does ttl checking, for a clean shutdown. The cache is no longer cleaning up after the first call to Close, repeated calls are safe though.

func (*Cache) Count

func (cache *Cache) Count() int

Count returns the number of items in the cache

func (*Cache) Get

func (cache *Cache) Get(key string) (interface{}, bool)

Get is a thread-safe way to lookup items Every lookup, also touches the item, hence extending it's life

func (*Cache) GetOrDefault added in v1.6.1

func (cache *Cache) GetOrDefault(key string, generator func(string) (interface{}, error)) (interface{}, error)

GetOrDefault is a thread-safe way to lookup items and invoke a function to create and store a default value if it is not. This operation is atomic, and the whole cache is locked while the generator is called to create the default value. Every lookup, also touches the item, hence extending it's life

func (*Cache) Purge

func (cache *Cache) Purge()

Purge will remove all entries

func (*Cache) Remove

func (cache *Cache) Remove(key string) bool

func (*Cache) Set

func (cache *Cache) Set(key string, data interface{})

Set is a thread-safe way to add new items to the map

func (*Cache) SetCheckExpirationCallback

func (cache *Cache) SetCheckExpirationCallback(callback checkExpireCallback)

SetCheckExpirationCallback sets a callback that will be called when an item is about to expire in order to allow external code to decide whether the item expires or remains for another TTL cycle

func (*Cache) SetExpirationCallback

func (cache *Cache) SetExpirationCallback(callback expireCallback)

SetExpirationCallback sets a callback that will be called when an item expires

func (*Cache) SetNewItemCallback

func (cache *Cache) SetNewItemCallback(callback expireCallback)

SetNewItemCallback sets a callback that will be called when a new item is added to the cache

func (*Cache) SetRemoveCallback added in v1.6.1

func (cache *Cache) SetRemoveCallback(callback expireCallback)

RemoveCallback sets a callback that will be called when an item is removed

func (*Cache) SetTTL

func (cache *Cache) SetTTL(ttl time.Duration)

func (*Cache) SetWithTTL

func (cache *Cache) SetWithTTL(key string, data interface{}, ttl time.Duration)

SetWithTTL is a thread-safe way to add new items to the map with individual ttl

func (*Cache) SkipTtlExtensionOnHit

func (cache *Cache) SkipTtlExtensionOnHit(value bool)

SkipTtlExtensionOnHit allows the user to change the cache behaviour. When this flag is set to true it will no longer extend TTL of items when they are retrieved using Get, or when their expiration condition is evaluated using SetCheckExpirationCallback.

Jump to

Keyboard shortcuts

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