LRU Cache v0.1.3 LruCache
This modules implements a simple LRU cache, using 2 ets tables for it.
For using it, you need to start it:
iex> LruCache.start_link(:my_cache, 1000)
Or add it to your supervisor tree, like: worker(LruCache, [:my_cache, 1000])
Using
iex> LruCache.start_link(:my_cache, 1000)
{:ok, #PID<0.60.0>}
iex> LruCache.put(:my_cache, "id", "value")
:ok
iex> LruCache.get(:my_cache, "id", touch = false)
"value"
To take some action when old keys are evicted from the cache when it is full,
you can pass an :evict_fn
option to LruCache.start_link/3
. This is
helpful for cleaning up processes that depend on values in the cache, or
logging, or instrumentation of cache evictions etc.
iex> evict = fn(key,value) -> IO.inspect("#{key}=#{value} evicted") end
iex> LruCache.start_link(:my_cache, 10, evict_fn: evict)
{:ok, #PID<0.60.0>}
Design
First ets table save the key values pairs, the second save order of inserted elements.
Summary
Functions
Removes the entry stored under the given key
from cache
Returns the value
associated with key
in cache
. If cache
does not contain key
,
returns nil. touch
defines, if the order in LRU should be actualized
Stores the given value
under key
in cache
. If cache
already has key
, the stored
value
is replaced by the new one. This updates the order of LRU cache
Creates an LRU of the given size as part of a supervision tree with a registered name
Updates a value
in cache
. If key
is not present in cache
then nothing is done.
touch
defines, if the order in LRU should be actualized. The function assumes, that
the element exists in a cache
Functions
Returns the value
associated with key
in cache
. If cache
does not contain key
,
returns nil. touch
defines, if the order in LRU should be actualized.
Stores the given value
under key
in cache
. If cache
already has key
, the stored
value
is replaced by the new one. This updates the order of LRU cache.
Creates an LRU of the given size as part of a supervision tree with a registered name
Options
:evict_fn
- function that accepts (key, value) and takes some action when keys are evicted when the cache is full.