ExResilience.Cache.Backend behaviour (ex_resilience v0.4.0)

Copy Markdown View Source

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

key()

@type key() :: term()

state()

@type state() :: term()

ttl_ms()

@type ttl_ms() :: non_neg_integer() | nil

value()

@type value() :: term()

Callbacks

get(key, state)

@callback get(key(), state()) :: {:hit, value(), state()} | {:miss, state()}

Looks up a key. Returns {:hit, value, state} on cache hit, or {:miss, state} on cache miss.

init(opts)

@callback init(opts :: keyword()) :: {:ok, state()} | {:error, term()}

Initializes the backend state from the given options.

invalidate(key, state)

@callback invalidate(key(), state()) :: {:ok, state()}

Removes the entry for key. If key is nil, removes all entries.

put(key, value, ttl_ms, state)

@callback put(key(), value(), ttl_ms(), state()) :: {:ok, state()}

Stores a value under key with an optional TTL in milliseconds. A nil TTL means the entry does not expire.

stats(state)

@callback stats(state()) :: map()

Returns a map of backend statistics (at minimum %{size: non_neg_integer()}).