メインコンテンツまでスキップ

Momento Cache を Elixir で使うためのチートシート

このページでは、Momento Cache を Go で素早く使ってみたい方のために必要となる基礎的な API 呼出しを解説しています。このコードのファイル全体はElixir SDK のページをご確認下さい

Momento SDK をインストール

最新バージョンの Momento Elixir SDK は Hex から利用可能です。

認証トークンを設定

Momento で認証するためには Momento 認証トークンが必要になります。Momento ウェブコンソールから取得可能です。 トークンを取得したら、環境変数に格納して Momento クライアントから使えるようにします:

export MOMENTO_AUTH_TOKEN=<your Momento token here>

CacheClient を設定

このコードで、それぞれの他の関数が呼び出す必要のある CacheClient struct を生成します。

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)

Momento Cache に新しいキャッシュを作成する

この関数を使ってアカウント内に新しいキャッシュを作成します。

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

アカウント内の既存のキャッシュをリストする

アカウント内のキャッシュの名前をシンプルにリストします。

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

項目をキャッシュに書き込む

書込み操作を行うシンプルな例です。client.set 呼出しでは、TTL はオプショナルです。もし TTL を渡すと、クライアント接続オブジェクトに設定されたデフォルトの TTL 値が上書きされます。

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

キャッシュから項目を読み出す

これは、キャッシュから項目を取得するためのシンプルな読み出し操作です。

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

コードを実行する

You can find complete, working examples in the Elixir SDK GitHub repo examples directory. 実行可能な完成された例は Elixir SDK GitHub レポジトリの examples ディレクトリをご覧下さい。

備考

これらの API 呼出し以上のものは、API リファレンスページで Momento API 呼出しの全種類の詳しい情報をご確認下さい。