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

.NETでMomento Topicsを始める

.NETとMomentoトピックをすぐに使い始める必要がある場合、このページには必要な基本的なAPIコールが含まれています。.NET SDKのサンプルを参照してください。

Momento SDKをインストールする

既存の.NETプロジェクトにクライアントライブラリをインストールします:

dotnet add package Momento.Sdk

Momento APIキーを取得する

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

export MOMENTO_API_KEY=<your api key here>

Note: セキュリティ強化のためには、APIキーを環境変数ではなく、AWS Secret ManagerやGCP Secret Managerのようなものに入れるのがベストプラクティスだが、ここではデモのためにAPIキーを使っています。

TopicClientのセットアップ

このコードでは、パブ/サブ・トピックとの対話に使用する TopicClient を作成します。

new TopicClient(
TopicConfigurations.Laptop.latest(),
new EnvMomentoTokenProvider("MOMENTO_API_KEY")
);

トピックにメッセージを公開する

これは、"topic "というトピックにメッセージを発行し、その返り値をキャッチして発行が成功したかどうかをチェックする例です。

var publishResponse =
await topicClient.PublishAsync("test-cache", "test-topic", "test-topic-value");
switch (publishResponse)
{
case TopicPublishResponse.Success:
Console.WriteLine("Successfully published message to 'test-topic'");
break;
case TopicPublishResponse.Error error:
throw new Exception($"An error occurred while publishing topic message: {error.ErrorCode}: {error}");
}

トピックを購読する

これは、"topic "というトピックを購読する例である。このトピックにメッセージがパブリッシュされると、ここのコードはそれを非同期に受信して表示する。

var produceCancellation = new CancellationTokenSource();
produceCancellation.CancelAfter(2000);

var subscribeResponse = await topicClient.SubscribeAsync("test-cache", "test-topic");
switch (subscribeResponse)
{
case TopicSubscribeResponse.Subscription subscription:
var cancellableSubscription = subscription.WithCancellation(produceCancellation.Token);

await Task.Delay(1_000);
await topicClient.PublishAsync("test-cache", "test-topic", "test-topic-value");
await Task.Delay(1_000);

await foreach (var message in cancellableSubscription)
{
switch (message)
{
case TopicMessage.Binary:
Console.WriteLine("Received unexpected binary message from topic.");
break;
case TopicMessage.Text text:
Console.WriteLine($"Received string message from topic: {text.Value}");
break;
case TopicMessage.Error error:
throw new Exception($"An error occurred while receiving topic message: {error.ErrorCode}: {error}");
default:
throw new Exception("Bad message received");
}
}
subscription.Dispose();
break;
case TopicSubscribeResponse.Error error:
throw new Exception($"An error occurred subscribing to a topic: {error.ErrorCode}: {error}");
}

コードの実行

完全な動作例は、.NET SDK GitHub repo examples directoryにあります。

備考

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