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

Momento Topics(pub/sub)API を使用する

Momento Topics は、分散型アプリケーションの各部分間でリアルタイム通信を可能にするメッセージングパターンです。トピックの値をパブリッシュ(プロデュース)し、トピックからサブスクライブ(コンシューム)することを可能にします。このページでは、Momento Topics で操作するための Momento API メソッドについて詳しく説明します。

詳細はMomento Topicsをご覧ください。

Topics のメソッド

Subscribe

このメソッドでは、ステートフルな接続を用いて新しい値を受け取るためにトピックをサブスクライブします。

名前説明
cacheNameStringトピックが存在するキャッシュの名前
topicNameStringサブスクライブするトピックの名前
これが サンプルコードです。
Coming soon.
メソッドのレスポンスオブジェクト
  • Success - サブスクリプションオブジェクトを返します。
  • Error

具体的な情報についてはレスポンスオブジェクトをご覧ください。

返されたサブスクリプションオブジェクトをforループに置くと、新しい値がトピックに公開される時にコードにイベントが送信されます。

const result = await topicClient.subscribe(cacheName, 'test-topic', {
onError: () => {
return;
},
onItem: (item: TopicItem) => {
console.log(`Received an item on subscription for 'test-topic': ${item.value().toString()}`);
return;
},
});
if (result instanceof TopicSubscribe.Subscription) {
console.log("Successfully subscribed to topic 'test-topic'");

console.log("Publishing a value to the topic 'test-topic'");
// Publish a value
await topicClient.publish(cacheName, 'test-topic', 'test-value');

console.log('Waiting for the published value to be received.');
await new Promise(resolve => setTimeout(resolve, 1000));

// Need to close the stream before the example ends or else the example will hang.
result.unsubscribe();
} else if (result instanceof TopicSubscribe.Error) {
throw new Error(
`An error occurred while attempting to subscribe to the topic 'test-topic' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Publish

メッセージをトピックにパブリッシュします。

名前説明
cacheNameStringトピックが存在するキャッシュの名前
topicNameString値をパブリッシュするトピック名
valueString / bytes トピックにパブリッシュする値
こちらがサンプルコードです。
Coming soon.
メソッドのレスポンスオブジェクト
  • Success
  • Error

具体的な情報についてはレスポンスオブジェクトをご覧ください。

const result = await topicClient.publish(cacheName, 'test-topic', 'test-topic-value');
if (result instanceof TopicPublish.Success) {
console.log("Value published to topic 'test-topic'");
} else if (result instanceof TopicPublish.Error) {
throw new Error(
`An error occurred while attempting to publish to the topic 'test-topic' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

TopicClient

ほとんどの Momento Cache API コールでは CacheClient を使用していますが、Topics については TopicClient オブジェクトを使用します。

new TopicClient({
configuration: TopicConfigurations.Default.latest(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});

Example apps using Momento Topics APIs

A growing list of example apps using the Momento Topics.

Momento Topicsを使用したアプリの例が続々と増えています。

  • サーバーレスで作成されたアイテムをパブリッシュするマイクロサービス このマイクロサービスはTypeScriptで書かれ、API Gateway、Lambda関数、Momento Topicsを使ってAWS上で実行される。(API Gateway上で適切なセキュリティが設定されていれば)他のサービスでも利用することができ、様々なトピックにメッセージを発行して他のアプリケーションから購読させることができます。この API に topicNametopicValue を渡すと、このサービスはその値をトピックにパブリッシュします。