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

JavaでMomento Cacheを始める

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

Momento SDKをインストールする

Momento SDKはMaven Centralで入手できます: `software.momento.java/sdkにあります。

ヒント

Maven Centralにアクセスして、SDKの最新バージョンを見つけてください。

既存のJavaプロジェクトにクライアント・ライブラリをインストールする:

Gradle

implementation("software.momento.java:sdk:1.x.x")

Maven

<dependency>
<groupId>software.momento.java</groupId>
<artifactId>sdk</artifactId>
<version>1.x.x</version>
</dependency>

APIキーの設定

Momentoで認証するには、Momento APIキーが必要です。 Momento Web Consoleから取得できます。 トークンを取得したら、Momento クライアントが利用できるように環境変数に保存します:

export MOMENTO_API_KEY=<your Momento API key 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_API_KEY"),
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 repo examples directoryに完全な動作例があります。

備考

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