ExResilience.Cache (ex_resilience v0.4.0)

Copy Markdown View Source

GenServer-based caching layer with pluggable backends.

Caches successful results of function calls, keyed by a caller-provided key. On cache hit the function is not executed. Errors pass through uncached.

Options

Backend-specific options are passed through to backend.init/1.

Examples

iex> opts = [name: :doc_cache, ttl: 5_000]
iex> {:ok, _} = ExResilience.Cache.start_link(opts)
iex> ExResilience.Cache.call(:doc_cache, :my_key, fn -> {:ok, 42} end)
{:ok, 42}
iex> ExResilience.Cache.call(:doc_cache, :my_key, fn -> raise "not called" end)
{:ok, 42}

Summary

Functions

Looks up key in the cache. On miss, executes fun and caches a successful result.

Returns a specification to start this module under a supervisor.

Removes the cached entry for key.

Starts a cache process.

Returns backend statistics for this cache instance.

Types

option()

@type option() ::
  {:name, atom()} | {:backend, module()} | {:ttl, non_neg_integer() | nil}

Functions

call(name, key, fun)

@spec call(atom(), term(), (-> term())) :: term()

Looks up key in the cache. On miss, executes fun and caches a successful result.

Successful results are {:ok, _} tuples or any non-error value. Error results ({:error, _} or :error) are returned without caching.

Examples

ExResilience.Cache.call(:my_cache, "user:1", fn ->
  {:ok, fetch_user(1)}
end)

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

invalidate(name, key)

@spec invalidate(atom(), term() | nil) :: :ok

Removes the cached entry for key.

Pass nil to clear all entries.

start_link(opts)

@spec start_link([option() | {atom(), term()}]) :: GenServer.on_start()

Starts a cache process.

See module docs for available options.

stats(name)

@spec stats(atom()) :: map()

Returns backend statistics for this cache instance.