Momento Cacheを使ったJavaのチートシート
JavaとMomento Cacheをすぐに使い始める必要がある場合、このページには基本的なAPIコールが記載されています。ビルド設定ファイルを含む実用的な例については、Java SDK examples を確認してください。
Momento clientライブラリのインストール
既存のJavaプロジェクトにクライアントライブラリをインストールします:
Gradle
implementation("software.momento.java:sdk:1.0.0")
Maven
<dependency>
<groupId>software.momento.java</groupId>
<artifactId>sdk</artifactId>
<version>1.0.0</version>
</dependency>
auth tokenを設定
Momentoで認証するには、Momento authトークンが必要です。 Momento Web コンソールから取得できます。 トークンを取得したら、Momento クライアントが利用できるように環境変数に保存します:
export MOMENTO_AUTH_TOKEN=<your Momento token here>
ライブラリをインポートし、CacheClient オブジェクトを返すように接続する
このコードでは、メイン関数、必要なインポート、および他の各関数が呼び出す必要のある CacheClient インスタンスを設定します。
package momento.client.example.doc_examples;
import java.time.Duration;
import momento.sdk.CacheClient;
import momento.sdk.auth.CredentialProvider;
import momento.sdk.config.Configurations;
public class CheatSheet {
public static void main(String[] args) {
try (final CacheClient cacheClient =
CacheClient.create(
CredentialProvider.fromEnvVar("MOMENTO_AUTH_TOKEN"),
Configurations.Laptop.v1(),
Duration.ofSeconds(60) /* defaultTTL for your cache items*/,
Duration.ofSeconds(10) /* eagerConnectionTimeout, default is 30 seconds */)) {
// ...
}
}
}
Momento Cacheに新しいキャッシュを作成する
アカウントに新しいキャッシュを作成するには、この関数を使います。
final CacheCreateResponse response = cacheClient.createCache("test-cache").join();
if (response instanceof CacheCreateResponse.Success) {
System.out.println("Cache 'test-cache' created");
} else if (response instanceof CacheCreateResponse.Error error) {
if (error.getCause() instanceof AlreadyExistsException) {
System.out.println("Cache 'test-cache' already exists");
} else {
throw new RuntimeException(
"An error occurred while attempting to create cache 'test-cache': "
+ error.getErrorCode(),
error);
}
}
アカウントに存在するキャッシュ名のリスト
アカウントに存在するキャッシュ名のリストを取得します。
final CacheListResponse response = cacheClient.listCaches().join();
if (response instanceof CacheListResponse.Success success) {
final String caches =
success.getCaches().stream().map(CacheInfo::name).collect(Collectors.joining("\n"));
System.out.println("Caches:\n" + caches);
} else if (response instanceof CacheListResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to list caches: " + error.getErrorCode(), error);
}
アイテムをキャッシュに書き込む
セット操作の簡単な例です。client.set呼び出しでは、TTLはオプションです。もしTTLを渡した場合、クライアント接続オブジェクトで設定されたデフォルトのTTL値が上書きされます。
final SetResponse response = cacheClient.set("test-cache", "test-key", "test-value").join();
if (response instanceof SetResponse.Success) {
System.out.println("Key 'test-key' stored successfully");
} else if (response instanceof SetResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to store key 'test-key' in cache 'test-cache': "
+ error.getErrorCode(),
error);
}
キャッシュからアイテムを読み込む
これは、キャッシュから項目を取得する単純な読み込み操作の例です。
final GetResponse response = cacheClient.get("test-cache", "test-key").join();
if (response instanceof GetResponse.Hit hit) {
System.out.println("Retrieved value for key 'test-key': " + hit.valueString());
} else if (response instanceof GetResponse.Miss) {
System.out.println("Key 'test-key' was not found in cache 'test-cache'");
} else if (response instanceof GetResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to get key 'test-key' from cache 'test-cache': "
+ error.getErrorCode(),
error);
}
コードを実行する
Java SDKのgithubリポジトリにあるexamplesディレクトリに動作例があります。
備考
これらの基本的なAPIコール以外にも、MomentoのAPIコールの詳細については、APIリファレンスページを参照してください。