CarCache (CarCache v0.1.1) View Source

Elixir CI Module Version Hex Docs Total Download License Last Updated

CLOCK with adaptive replacement (CAR) cache, based on the following paper:

CAR: Clock with Adaptive Replacement

CAR is a self tuning cache that strives to find a balance between frequently accessed items and recently accessed items.

CAR is fairly similar to ARC Adaptive Replacement Cache for which there is a good introductory explanation here: Adaptive Replacement Cache

Usage

The cache must be given a name and a max_size when started.

{:ok, _pid} = CarCache.start_link(name: :my_cache, max_size: 1_000)

After the process has started you can use it based on it's name:

> CarCache.get(:my_cache, :foo)
nil

> CarCache.insert(:my_cache, :foo, :bar)
:ok

> CarCache.get(:my_cache, :foo)
:bar

Link to this section Summary

Functions

Returns a specification to start this module under a supervisor.

Delete a key from the cache

Fetches the value from the cache if it exists, otherwise executes fallback.

Get a value from the cache, if it exists in the cache

Insert a value into the cache under a given key

Starts a new cache.

Link to this section Functions

Returns a specification to start this module under a supervisor.

See Supervisor.

Specs

delete(atom(), any()) :: any()

Delete a key from the cache

Example

CarCache.delete(:my_cache, user_id)
Link to this function

fetch(name, key, fallback)

View Source

Specs

fetch(atom(), any(), (() -> {:commit, any()} | {:ignore, any()})) :: any()

Fetches the value from the cache if it exists, otherwise executes fallback.

The fallback function can return either {:commit, any()} or {:ignore, any()}. If {:commit, any()} is returned, the value will be stored in the cache

Example

CarCache.get(:my_cache, user_id, fn ->
  case Profile.get(user_id) do
    {:ok, profile} -> {:commit, profile}
    {:error, _reason} = error -> {:ignore, error}
  end
end)

Specs

get(atom(), any()) :: any()

Get a value from the cache, if it exists in the cache

Example

CarCache.get(:my_cache, user_id)

Specs

put(atom(), any(), any()) :: :ok

Insert a value into the cache under a given key

Example

CarCache.put(:my_cache, user_id, profile)

Starts a new cache.

Options:

  • :name - Required.

  • :max_size - Required.