SDK for JavaScriptストリーミング・クイックスタート
このクイックスタートでは、Oracle Cloud Infrastructure (OCI) SDK for TypeScriptおよびJavaScriptおよびOracle Cloud Infrastructure Streamingを使用して、メッセージを公開および消費する方法を示します。
主要概念およびストリーミングの詳細は、ストリーミングの概要を参照してください。OCI SDKの使用の詳細は、SDKガイドを参照してください。
前提条件
-
SDK for TypeScript and JavaScriptを使用するには、次が必要です:
- Oracle Cloud Infrastructureアカウント。
- そのアカウントで作成され、必要な権限を付与するポリシーがあるグループに含まれるユーザー。このユーザーは、自分自身であるか、またはAPIをコールする必要がある別の個人/システムです。新しいユーザー、グループ、コンパートメントおよびポリシーの設定方法の例は、ユーザーの追加を参照してください。使用する一般的なポリシーのリストは、共通ポリシーを参照してください。
- APIリクエストの署名に使用されるキー・ペア(公開キーがOracleにアップロードされている)。秘密キーはAPIをコールするユーザーのみが所有する必要があります。詳細は、開始を参照してください。
- ストリームのメッセージ・エンドポイントおよびOCIDを収集します。ストリームの詳細を表示する手順は、ストリームおよびストリーム・プールのリストを参照してください。このクイックスタートの目的では、ストリームでパブリック・エンドポイントを使用し、Oracleで暗号化を管理する必要があります。既存のストリームがない場合は、「ストリームの作成」および「ストリーム・プールの作成」を参照してください。
- Node.jsバージョン8.x以降。最新の長期サポート(LTS)バージョンをダウンロードします。
- Visual Code Studio (推奨)またはその他の統合開発環境(IDE)。
-
パスに
npm
を含むコマンド・プロンプトを開き、このクイックスタートのコードを保持するディレクトリ(wd
など)に移動し、次のコマンドを実行してOCI SDK for JavaScriptをインストールします:npm install oci-sdk
- 有効なSDK構成ファイルがあることを確認します。本番環境では、インスタンス・プリンシパル認可を使用する必要があります。
メッセージの生成
wd
ディレクトリから、Visual Studio Codeなどのお気に入りのエディタを開きます。前提条件を満たした後、このディレクトリにJavaScript用のoci-sdk
パッケージがすでにインストールされている必要があります。-
次のコードを使用して、
wd
ディレクトリにProducer.js
という名前のファイルを作成します。次のコード・スニペットの変数ociConfigFile
、ociProfileName
、ociStreamOcid
およびociMessageEndpointForStream
の値は、テナンシに適用可能な値で置き換えてください。const common = require("oci-common"); const st = require("oci-streaming"); // OCI SDK package for OSS const ociConfigFile = "<config_file_path>"; const ociProfileName = "<config_file_profile_name>"; const ociMessageEndpointForStream = "<stream_message_endpoint>"; const ociStreamOcid = "<stream_OCID>"; // provide authentication for OCI and OSS const provider = new common.ConfigFileAuthenticationDetailsProvider(ociConfigFile, ociProfileName); async function main() { // OSS client to produce and consume messages from a Stream in OSS const client = new st.StreamClient({ authenticationDetailsProvider: provider }); client.endpoint = ociMessageEndpointForStream; // build up a putRequest and publish some messages to the stream let messages = []; for (let i = 1; i <= 3; i++) { let entry = { key: Buffer.from("messageKey" + i).toString("base64"), value: Buffer.from("messageValue" + i).toString("base64") }; messages.push(entry); } console.log("Publishing %s messages to stream %s.", messages.length, ociStreamOcid); const putMessageDetails = { messages: messages }; const putMessagesRequest = { putMessagesDetails: putMessageDetails, streamId: ociStreamOcid }; const putMessageResponse = await client.putMessages(putMessagesRequest); for (var entry of putMessageResponse.putMessagesResult.entries) console.log("Published messages to parition %s, offset %s", entry.partition, entry.offset); } main().catch((err) => { console.log("Error occurred: ", err); });
-
wd
ディレクトリから、次のコマンドを実行します:node run Producer.js
- コンソールを使用して、ストリームに送信された最新のメッセージを表示し、生成が成功したことを確認します。
メッセージの消費
- 最初に、メッセージを消費するストリームにメッセージが含まれていることを確認します。コンソールを使用してテスト・メッセージを生成するか、このクイックスタートで作成したストリームおよびメッセージを使用できます。
wd
ディレクトリから、Visual Studio Codeなどのお気に入りのエディタを開きます。前提条件を満たした後、このディレクトリにJavaScript用のoci-sdk
パッケージがすでにインストールされている必要があります。-
次のコードを使用して、ディレクトリ
wd
にConsumer.js
という名前のファイルを作成します。次のコード・スニペットの変数ociConfigFile
、ociProfileName
、ociStreamOcid
およびociMessageEndpointForStream
の値は、テナンシに適用可能な値で置き換えてください。const common = require("oci-common"); const st = require("oci-streaming"); // OCI SDK package for OSS const ociConfigFile = "<config_file_path>"; const ociProfileName = "<config_file_profile_name>"; const ociMessageEndpointForStream = "<stream_message_endpoint>"; const ociStreamOcid = "<stream_OCID>"; // provide authentication for OCI and OSS const provider = new common.ConfigFileAuthenticationDetailsProvider(ociConfigFile, ociProfileName); const consumerGroupName = "exampleGroup"; const consumerGroupInstanceName = "exampleInstance-1"; async function main() { // OSS client to produce and consume messages from a Stream in OSS const client = new st.StreamClient({ authenticationDetailsProvider: provider }); client.endpoint = ociMessageEndpointForStream; // A cursor can be created as part of a consumer group. // Committed offsets are managed for the group, and partitions // are dynamically balanced amongst consumers in the group. console.log("Starting a simple message loop with a group cursor"); const groupCursor = await getCursorByGroup(client, ociStreamOcid, consumerGroupName, consumerGroupInstanceName); await consumerMsgLoop(client, ociStreamOcid, groupCursor); } main().catch((err) => { console.log("Error occurred: ", err); }); async function consumerMsgLoop(client, streamId, initialCursor) { let cursor = initialCursor; for (var i = 0; i < 10; i++) { const getRequest = { streamId: streamId, cursor: cursor, limit: 2 }; const response = await client.getMessages(getRequest); console.log("Read %s messages.", response.items.length); for (var message of response.items) { if (message.key !== null) { console.log("%s: %s", Buffer.from(message.key, "base64").toString(), Buffer.from(message.value, "base64").toString()); } else{ console.log("Null: %s", Buffer.from(message.value, "base64").toString() ); } } // getMessages is a throttled method; clients should retrieve sufficiently large message // batches, as to avoid too many http requests. await delay(2); cursor = response.opcNextCursor; } } async function getCursorByGroup(client, streamId, groupName, instanceName) { console.log("Creating a cursor for group %s, instance %s.", groupName, instanceName); const cursorDetails = { groupName: groupName, instanceName: instanceName, type: st.models.CreateGroupCursorDetails.Type.TrimHorizon, commitOnGet: true }; const createCursorRequest = { createGroupCursorDetails: cursorDetails, streamId: streamId }; const response = await client.createGroupCursor(createCursorRequest); return response.cursor.value; } async function delay(s) { return new Promise(resolve => setTimeout(resolve, s * 1000)); }
-
wd
ディレクトリから、次のコマンドを実行します:node run Consumer.js
-
次のようなメッセージが表示されます:
Starting a simple message loop with a group cursor Creating a cursor for group exampleGroup, instance exampleInstance-1. Read 1 messages. Null: Example Test Message 0 Read 1 messages. Null: Example Test Message 0 Read 1 messages. Null: Example Test Message 0 Read 2 messages. Null: Example Test Message 0 Null: Example Test Message 0 Read 2 messages. Null: Example Test Message 0 Null: Example Test Message 0
次のステップ
詳細は、次のリソースを参照してください:
- OCI SDK for JavaScript (GitHub上)
- OCI SDK for JavaScriptの例