KotlinでMomentoキャッシュを始める
KotlinとMomento Cacheをすぐに使い始める必要がある場合、このページには必要な基本的なAPIコールが含まれています。ビルド設定ファイルを含む完全で実用的な例については、Kotlin SDK examples を確認してください。
Momento SDKをインストールする
Momento SDKはMaven Centralで入手できます: software.momento.kotlin/sdk
にあります。
ヒント
Maven Centralにアクセスして、SDKの最新バージョンを見つけてください。
Install the client library in an existing Kotlin project:
Gradle
implementation("software.momento.kotlin:sdk:x.x.x")
Maven
<dependency>
<groupId>software.momento.kotlin</groupId>
<artifactId>sdk</artifactId>
<version>x.x.x</version>
</dependency>
APIキーの設定
Momentoで認証するには、Momento APIキーが必要です。 Momento Web Console](https://console.gomomento.com/caches)から取得できます。 APIキーを取得したら、Momento クライアントが利用できるように環境変数に保存します:
export MOMENTO_API_KEY=<your Momento API key here>
ライブラリをインポートして接続し、CacheClient オブジェクトの初期化
このコードでは、メイン関数、必要なインポート、および他の各関数が呼び出す必要のある CacheClient インスタンス化を設定します。
package software.momento.example.doc_examples
import kotlinx.coroutines.runBlocking
import software.momento.kotlin.sdk.CacheClient
import software.momento.kotlin.sdk.auth.CredentialProvider
import software.momento.kotlin.sdk.config.Configurations
import software.momento.kotlin.sdk.responses.cache.GetResponse
import kotlin.time.Duration.Companion.seconds
fun main() = runBlocking {
CacheClient(
CredentialProvider.fromEnvVar("MOMENTO_API_KEY"),
Configurations.Laptop.latest,
60.seconds
).use { client ->
//...
}
}
Momento Cacheに新しいキャッシュを作成する
この機能を使用して、アカウントに新しいキャッシュを作成します。
when (val response = cacheClient.createCache("test-cache")) {
is CacheCreateResponse.Success -> println("Cache 'test-cache' created")
is CacheCreateResponse.AlreadyExists -> println("Cache 'test-cache' already exists")
is CacheCreateResponse.Error -> throw RuntimeException(
"An error occurred while attempting to create cache 'test-cache': ${response.errorCode}", response
)
}