All Projects → ReneKroon → ttlcache

ReneKroon / ttlcache

Licence: MIT license
An in-memory cache with item expiration and generics

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to ttlcache

Higgledy
Higher-kinded data via generics
Stars: ✭ 153 (-67.31%)
Mutual labels:  generics
rust-amplify
Amplifying Rust language capabilities: multiple generic trait implementations, type wrappers, bit-precise numerics, derive macros
Stars: ✭ 38 (-91.88%)
Mutual labels:  generics
truthy
Package truthy provides truthy condition testing with Go generics
Stars: ✭ 31 (-93.38%)
Mutual labels:  generics
Staticvec
Implements a fixed-capacity stack-allocated Vec alternative backed by an array, using const generics.
Stars: ✭ 236 (-49.57%)
Mutual labels:  generics
lancet
A comprehensive, efficient, and reusable util function library of go.
Stars: ✭ 2,228 (+376.07%)
Mutual labels:  generics
Java-Interview-Programs
Core Java Projects with complete source code
Stars: ✭ 48 (-89.74%)
Mutual labels:  generics
Go generics
Templates, generics engine for Go
Stars: ✭ 141 (-69.87%)
Mutual labels:  generics
go2generics
🧪 A chunk of experiments and demos about Go 2 generics design (type parameter & type set)
Stars: ✭ 146 (-68.8%)
Mutual labels:  generics
go-ringbuf
Lock-free MPMC Ring Buffer (Generic) for SMP, in golang. Some posts in chinese:
Stars: ✭ 43 (-90.81%)
Mutual labels:  generics
generics
Deprecated! See https://github.com/golang-design/go2generics.
Stars: ✭ 26 (-94.44%)
Mutual labels:  generics
Arrow Meta
Functional companion to Kotlin's Compiler
Stars: ✭ 246 (-47.44%)
Mutual labels:  generics
go-generics
Go的泛型文档、代码、讨论
Stars: ✭ 43 (-90.81%)
Mutual labels:  generics
Java-Programs
Java Practiced Problems including concepts of OOPS, Interface, String , Collection.
Stars: ✭ 51 (-89.1%)
Mutual labels:  generics
Syncmap
A typed implementation of the Go sync.Map using code generation
Stars: ✭ 200 (-57.26%)
Mutual labels:  generics
ViewControllersFactory
Instantiate your ViewControllers easily with this small factory class
Stars: ✭ 26 (-94.44%)
Mutual labels:  generics
Auth Adt
Authenticated Data Structures Generically
Stars: ✭ 150 (-67.95%)
Mutual labels:  generics
async
Synchronization and asynchronous computation package for Go
Stars: ✭ 104 (-77.78%)
Mutual labels:  generics
ConfuserExPlugins
Transforms all types to generics, and all constructor calls and method calls into generic call factories.
Stars: ✭ 32 (-93.16%)
Mutual labels:  generics
heidi
heidi : tidy data in Haskell
Stars: ✭ 24 (-94.87%)
Mutual labels:  generics
parco
🏇🏻 generalist, fast and tiny binary parser and compiler generator, powered by Go 1.18+ Generics
Stars: ✭ 57 (-87.82%)
Mutual labels:  generics

TTLCache - an in-memory cache with item expiration

Go Reference Build Status Coverage Status Go Report Card

Features

  • Simple API.
  • Type parameters.
  • Item expiration and automatic deletion.
  • Automatic expiration time extension on each Get call.
  • Loader interface that is used to load/lazily initialize missing cache items.
  • Subscription to cache events (insertion and eviction).
  • Metrics.
  • Configurability.

Installation

go get github.com/jellydator/ttlcache/v3

Usage

The main type of ttlcache is Cache. It represents a single in-memory data store.

To create a new instance of ttlcache.Cache, the ttlcache.New() function should be called:

func main() {
	cache := ttlcache.New[string, string]()
}

Note that by default, a new cache instance does not let any of its items to expire or be automatically deleted. However, this feature can be activated by passing a few additional options into the ttlcache.New() function and calling the cache.Start() method:

func main() {
	cache := ttlcache.New[string, string](
		ttlcache.WithTTL[string, string](30 * time.Minute),
	)

	go cache.Start() // starts automatic expired item deletion
}

Even though the cache.Start() method handles expired item deletion well, there may be times when the system that uses ttlcache needs to determine when to delete the expired items itself. For example, it may need to delete them only when the resource load is at its lowest (e.g., after midnight, when the number of users/HTTP requests drops). So, in situations like these, instead of calling cache.Start(), the system could periodically call cache.DeleteExpired():

func main() {
	cache := ttlcache.New[string, string](
		ttlcache.WithTTL[string, string](30 * time.Minute),
	)

	for {
		time.Sleep(4 * time.Hour)
		cache.DeleteExpired()
	}
}

The data stored in ttlcache.Cache can be retrieved and updated with Set, Get, Delete, etc. methods:

func main() {
	cache := ttlcache.New[string, string](
		ttlcache.WithTTL[string, string](30 * time.Minute),
	)

	// insert data
	cache.Set("first", "value1", ttlcache.DefaultTTL)
	cache.Set("second", "value2", ttlcache.NoTTL)
	cache.Set("third", "value3", ttlcache.DefaultTTL)

	// retrieve data
	item := cache.Get("first")
	fmt.Println(item.Value(), item.ExpiresAt())

	// delete data
	cache.Delete("second")
	cache.DeleteExpired()
	cache.DeleteAll()
}

To subscribe to insertion and eviction events, cache.OnInsertion() and cache.OnEviction() methods should be used:

func main() {
	cache := ttlcache.New[string, string](
		ttlcache.WithTTL[string, string](30 * time.Minute),
		ttlcache.WithCapacity[string, string](300),
	)

	cache.OnInsertion(func(item *ttlcache.Item[string, string]) {
		fmt.Println(item.Value(), item.ExpiresAt())
	})
	cache.OnEviction(func(reason ttlcache.EvictionReason, item *ttlcache.Item[string, string]) {
		if reason == ttlcache.EvictionReasonCapacityReached {
			fmt.Println(item.Key(), item.Value())
		}
	})

	cache.Set("first", "value1", ttlcache.DefaultTTL)
	cache.DeleteAll()
}

To load data when the cache does not have it, a custom or existing implementation of ttlcache.Loader can be used:

func main() {
	loader := ttlcache.LoaderFunc[string, string](
		func(c *ttlcache.Cache[string, string], key string) *ttlcache.Item[string, string] {
			// load from file/make an HTTP request
			item := c.Set("key from file", "value from file")
			return item
		},
	)
	cache := ttlcache.New[string, string](
		ttlcache.WithLoader[string, string](loader),
	)

	item := cache.Get("key from file")
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].