Simple key/value cache for Go
Go to file
Basit Ali d18573b146
Create LICENSE
2022-07-14 02:42:38 +05:00
LICENSE Create LICENSE 2022-07-14 02:42:38 +05:00
README.md Create README.md 2022-07-07 13:16:07 +05:00
cache.go cache eviction using sweeper 2022-04-05 04:11:54 +05:00
delete_expired.go eviction callback 2022-04-06 15:19:15 +05:00
errors.go cache eviction using sweeper 2022-04-05 04:11:54 +05:00
flush.go cache eviction using sweeper 2022-04-05 04:10:40 +05:00
get.go return data instead of pair 2022-03-29 22:09:32 +05:00
go.mod init 2021-12-07 17:34:49 +05:00
my_cache.go finalizer bug, ignoring gc for now 2022-04-06 16:10:11 +05:00
remove.go init 2021-12-07 17:34:49 +05:00
set.go refactor 2022-04-05 04:18:49 +05:00
sweeper.go cache eviction using sweeper 2022-04-05 04:10:40 +05:00
value.go refactor 2022-04-05 04:18:49 +05:00

README.md

go-cache

Simple thread safe key/value cache for Go.

Usage

You can initialize the cache using:

    cache = gocache.NewCache()

And perform the operations using:

   // GET a value using key, which returns (value, error)
   cache.Get(key)
   
   // SET a value using key
   cache.Set(key, value)
   
   // REMOVE a key/value pair using key
   cache.Remove(key)
   
   // And FLUSH, which removes all items from the cache
   cache.Flush()

Cache Expiration

You can also add an expiration to the cache, expired cache will be auto deleted by the sweeper.

To initialize a cache using sweeper we can use:

    cache := NewCacheWithSweeper(10 * time.Minute, 10 * time.Minute, decisionFunc, onEviction)

Here, first two parameters are interval and expireAfter, sweeper will run in the background after specified interval to check for expired cache to delete.

The decisionFunc and onEviction are optional functions with the following signature:

    decisionFunc func(v interface{}) bool
    
    onEviction func(k string, v interface{})

We can use decisionFunc as a callback, it will be called by the cache before deleting a key/value, it takes in the value to delete and returns true to delete and false for not deleting a key/value pair even after expired.

The onEviction is a callback which will be called every time a cache is deleted with its key/value as parameters.