Skip to main content

Getting Started with Momento Cache in Elixir

If you need to get going quickly with Elixir and Momento Cache, this page contains the basic API calls you'll need. Check the Elixir SDK examples for complete, working examples.

Install the Momento SDK

The latest version of the Momento Elixir SDK is available on Hex.

Set up your API key

You'll need a Momento auth token to authenticate with Momento. You can get one from the Momento Web Console. Once you have your token, store it in an environment variable so that the Momento client can consume it:

export MOMENTO_API_KEY=<your Momento token here>

Set up a CacheClient

This code creates the CacheClient struct that each of the other functions requires.

alias Momento.CacheClient

config = Momento.Configurations.Laptop.latest()
credential_provider = Momento.Auth.CredentialProvider.from_env_var!("MOMENTO_AUTH_TOKEN")
default_ttl_seconds = 60.0
client = CacheClient.create!(config, credential_provider, default_ttl_seconds)

Create a new cache in Momento Cache

Use this function to create a new cache in your account.

case Momento.CacheClient.create_cache(client, "test-cache") do
{:ok, _} ->
IO.puts("Cache 'test-cache' created")

:already_exists ->
:ok

{:error, error} ->
IO.puts(
"An error occurred while attempting to create cache 'test-cache': #{error.error_code}"
)

raise error
end

List the names of existing caches in your account

A simple list of the names of caches for the account.

case Momento.CacheClient.list_caches(client) do
{:ok, result} ->
IO.puts("Caches:")
IO.inspect(result.caches)

{:error, error} ->
IO.puts("An error occurred while attempting to list caches: #{error.error_code}")
raise error
end

Write an item to a cache

A simple example of doing a set operation. In the CacheClient.set() call, the TTL is optional. If you did pass it in, this would override the default TTL value set with the client connection object.

case Momento.CacheClient.set(client, "test-cache", "test-key", "test-value") do
{:ok, _} ->
IO.puts("Key 'test-key' stored successfully")

{:error, error} ->
IO.puts(
"An error occurred while attempting to store key 'test-key' in cache 'test-cache': #{error.error_code}"
)

raise error
end

Read an item from a cache

This is an example of a simple read operation to get an item from a cache.

case Momento.CacheClient.get(client, "test-cache", "test-key") do
{:ok, hit} ->
IO.puts("Retrieved value for key 'test-key': #{hit.value}")

:miss ->
IO.puts("Key 'test-key' was not found in cache 'test-cache'")

{:error, error} ->
IO.puts(
"An error occurred while attempting to get key 'test-key' from cache 'test-cache': #{error.error_code}"
)

raise error
end

Running the code

You can find complete, working examples in the Elixir SDK GitHub repo examples directory.

info

Beyond these basic API calls check out the API reference page for more information on the full assortment of Momento API calls.