Behaviour for pluggable cache backends.
Implement this behaviour to use a custom caching library (Cachex, ConCache, etc.) as a cache layer backend.
Example
A minimal in-memory backend:
defmodule MyBackend do
@behaviour ExResilience.Cache.Backend
@impl true
def init(_opts), do: {:ok, %{}}
@impl true
def get(key, state) do
case Map.fetch(state, key) do
{:ok, value} -> {:hit, value, state}
:error -> {:miss, state}
end
end
@impl true
def put(key, value, _ttl, state), do: {:ok, Map.put(state, key, value)}
@impl true
def invalidate(key, state), do: {:ok, Map.delete(state, key)}
@impl true
def stats(state), do: %{size: map_size(state)}
end
Summary
Callbacks
Looks up a key. Returns {:hit, value, state} on cache hit,
or {:miss, state} on cache miss.
Initializes the backend state from the given options.
Removes the entry for key. If key is nil, removes all entries.
Stores a value under key with an optional TTL in milliseconds.
A nil TTL means the entry does not expire.
Returns a map of backend statistics (at minimum %{size: non_neg_integer()}).
Types
@type key() :: term()
@type state() :: term()
@type ttl_ms() :: non_neg_integer() | nil
@type value() :: term()
Callbacks
Looks up a key. Returns {:hit, value, state} on cache hit,
or {:miss, state} on cache miss.
Initializes the backend state from the given options.
Removes the entry for key. If key is nil, removes all entries.
Stores a value under key with an optional TTL in milliseconds.
A nil TTL means the entry does not expire.
Returns a map of backend statistics (at minimum %{size: non_neg_integer()}).