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

ElixirでMomento Cacheを始める

ElixirとMomento Cacheをすぐに使い始める必要がある場合、このページには必要な基本的なAPIコールが含まれています。完全で実用的な例については、Elixir SDK examples を確認してください。

Momento SDKをインストールする

Momento Elixir SDKの最新バージョンはHexにあります。

APIキーの設定

Momentoで認証するには、Momento認証トークンが必要です。 Momento Web Console](https://console.gomomento.com/caches)から取得できます。 トークンを取得したら、Momento クライアントが利用できるように環境変数に保存します:

export MOMENTO_AUTH_TOKEN=<your Momento token here>

CacheClient のセットアップ

このコードは、他の各関数が必要とする CacheClient 構造を作成します。

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

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

セット操作の単純な例。CacheClient.set() 呼び出しでは、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

コードの実行

Elixir SDK GitHub repo examples directoryに完全なサンプルがあります。

備考

これらの基本的なAPIコール以外にも、MomentoのAPIコールの詳細については、APIリファレンスページをチェックしてください。