建立範例訊息應用程式 - AWS SDK for JavaScript

AWS SDK for JavaScript V3 參API考指南詳細描述了 AWS SDK for JavaScript 版本 3(V3)的所有API操作。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

建立範例訊息應用程式

您可以使AWS用和 Amazon Simple Queue Service (Amazon SQS) 建立傳送AWS SDK for JavaScript和擷取訊息的應用程式。訊息會儲存在先進先出 (FIFO) 佇列中,以確保訊息的順序一致。例如,儲存在佇列中的第一個訊息是從佇列讀取的第一封郵件。

注意

如需 Amazon SQS 的詳細資訊,請參閱什麼是 Amazon 簡單佇列服務

在本教學課程中,您會建立名為「AWS訊息」的 Node.js 應用程式。

完成成本:本文件中包含的AWS服務包含在AWS免費方案中。

附註:請務必在完成本教學課程時終止您建立的所有資源,以確保不會向您收費。

必要條件

若要設定和執行此範例,您必須先完成這些任務:

  • 設置項目環境以運行這些節點 TypeScript 示例,並安裝所需AWS SDK for JavaScript的第三方模塊。按照上的說明進行操作 GitHub

  • 透過使用者登入資料建立共用組態檔。有關提供共用認證檔案的詳細資訊,請參閱 AWSSDK 和工具參考指南中的共用設定和認證檔案。

重要

此範例使用電子郵件密碼 6 (ES6)。這需要 Node.js 版本 13.x 或更高版本。要下載並安裝最新版本的 Node.js,請參閱 Node.js 下載。

但是,如果您更喜歡使用 CommonJS 語法,請參閱JavaScript ES6/共同語法

建立資AWS源

本教學課程需要下列資源。

您可以手動建立此資源,但建議您使用 AWS CloudFormation (AWS CloudFormation) 佈建這些資源,如本教學課程所述。

注意

這AWS CloudFormation是一個軟體開發架構,可讓您定義雲端應用程式資源。如需詳細資訊,請參閱《 使用者指南》AWS CloudFormation

使用建立AWS資源 AWS CloudFormation

AWS CloudFormation 可讓您以可預期和重複的方式建立及佈建 AWS 基礎設施部署。如需 AWS CloudFormation 的相關資訊,請參閱《 使用者指南》AWS CloudFormation

要使用以下命AWS CloudFormation令創建堆棧AWS CLI:

  1. 安裝並設定AWS CLI以下AWS CLI使用者指南中的指示。

  2. 在項目文件夾的根目錄setup.yaml中創建一個名為的文件,然後將此處的內容複製 GitHub到其中。

    注意

    AWS CloudFormation範本是使用中AWS CDK提供的來產生的 GitHub。如需關於 AWS CDK 的詳細資訊,請參閱《AWS Cloud Development Kit (AWS CDK) 開發人員指南》。

  3. 從命令列執行下列命令,並以堆疊的唯一名稱取代 STACK_NAME

    重要

    堆疊名稱在AWS區域和AWS帳戶中必須是唯一的。您最多可以指定 128 個字元,且允許使用數字和連字號。

    aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM

    若要取得有關指create-stack令參數的更多資訊,請參閱《指AWS CLI令參考指南》和《AWS CloudFormation使用指南》

    若要檢視建立的資源,請AWS CloudFormation在AWS管理主控台中開啟,選擇堆疊,然後選取 [資源] 索引標籤。

瞭解AWS訊息應用程式

若要將訊息傳送至 SQS 佇列,請將訊息輸入應用程式,然後選擇傳送。

傳送訊息後,應用程式會顯示訊息。

您可以選擇整個清除,以清除 Amazon SQS 佇列中的訊息。這會導致佇列空白,應用程式中不會顯示任何訊息。

以下說明應用程式如何處理訊息:

  • 用戶選擇他們的名稱並輸入他們的消息,並提交啟動函數的消息。pushMessage

  • pushMessage擷取 Amazon SQS 佇列網址,然後傳送訊息文字具有唯一訊息 ID 值 (GUID) 的訊息,並將使用者傳送至 Amazon SQS 佇列。

  • pushMessage從 Amazon SQS 佇列擷取訊息、擷取每則訊息的使用者和訊息,然後顯示訊息。

  • 使用者可以清除訊息,從 Amazon SQS 佇列和使用者介面刪除訊息。

創建 HTML 頁面

現在,您可以建立應用程式圖形化使用者介面 (GUI) 所需的 HTML 檔案。建立名為 index.html 的檔案。將下面的代碼複製並粘貼到index.html。這個 HTML 引用main.js。這是 index.js 的捆綁版本,其中包括所需的AWS SDK for JavaScript模塊。

<!doctype html> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" > <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="./images/favicon.ico" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="./css/styles.css" /> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <script src="./js/main.js"></script> <style> .messageelement { margin: auto; border: 2px solid #dedede; background-color: #d7d1d0; border-radius: 5px; max-width: 800px; padding: 10px; margin: 10px 0; } .messageelement::after { content: ""; clear: both; display: table; } .messageelement img { float: left; max-width: 60px; width: 100%; margin-right: 20px; border-radius: 50%; } .messageelement img.right { float: right; margin-left: 20px; margin-right: 0; } </style> </head> <body> <div class="container"> <h2>AWS Sample Messaging Application</h2> <div id="messages"></div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Sender:</span> </div> <select name="cars" id="username"> <option value="Scott">Brian</option> <option value="Tricia">Tricia</option> </select> </div> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">Message:</span> </div> <textarea class="form-control" id="textarea" aria-label="With textarea" ></textarea> <button type="button" onclick="pushMessage()" id="send" class="btn btn-success" > Send </button> <button type="button" onclick="purge()" id="refresh" class="btn btn-success" > Purge </button> </div> <!-- All of these child items are hidden and only displayed in a FancyBox ------------------------------------------------------> <div id="hide" style="display: none"> <div id="base" class="messageelement"> <img src="../public/images/av2.png" alt="Avatar" class="right" style="width: 100%" /> <p id="text">Excellent! So, what do you want to do today?</p> <span class="time-right">11:02</span> </div> </div> </div> </body> </html>

此代碼也可以在這裡找到 GitHub

建立瀏覽器指令碼

在本主題中,您會建立應用程式的瀏覽器指令碼。建立瀏覽器指令碼後,您可以將其捆綁到名為的檔案中,main.js如中所述捆綁 JavaScript

建立名為 index.js 的檔案。將代碼從這裡複製並粘貼 GitHub到其中。

此代碼將在以下各節中進行說明:

組態

首先,建立一個libs目錄,建立名為sqsClient.js的檔案,建立所需的 Amazon SQS 用戶端物件。替換每個區域身份 _POOL_ID

注意

使用您在建立資AWS源 其中建立的 Amazon Cognito 身分識別集區的識別碼。

import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers"; import {SQSClient} from "@aws-sdk/client-sqs"; const REGION = "REGION"; //e.g. "us-east-1" const IdentityPoolId = "IDENTITY_POOL_ID"; const sqsClient = new SQSClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IdentityPoolId }), });

在中index.js,匯入必要的AWS SDK for JavaScript模組和指令。以您在中建立的 Amazon SQS 佇列名稱取代 SQS 佇列的名稱。建立資AWS源

import { GetQueueUrlCommand, SendMessageCommand, ReceiveMessageCommand, PurgeQueueCommand, } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; const QueueName = "SQS_QUEUE_NAME"; // The Amazon SQS queue name, which must end in .fifo for this example.

民意科技

populateChat函數 onload 會自動擷取 Amazon SQS 佇列的 URL,並擷取佇列中的所有訊息,並顯示這些訊息。

$(function () { populateChat(); }); const populateChat = async () => { try { // Set the Amazon SQS Queue parameters. const queueParams = { QueueName: QueueName, Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }; // Get the Amazon SQS Queue URL. const data = await sqsClient.send(new GetQueueUrlCommand(queueParams)); console.log("Success. The URL of the SQS Queue is: ", data.QueueUrl); // Set the parameters for retrieving the messages in the Amazon SQS Queue. var getMessageParams = { QueueUrl: data.QueueUrl, MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], VisibilityTimeout: 20, WaitTimeSeconds: 20, }; try { // Retrieve the messages from the Amazon SQS Queue. const data = await sqsClient.send( new ReceiveMessageCommand(getMessageParams) ); console.log("Successfully retrieved messages", data.Messages); // Loop through messages for user and message body. var i; for (i = 0; i < data.Messages.length; i++) { const name = data.Messages[i].MessageAttributes.Name.StringValue; const body = data.Messages[i].Body; // Create the HTML for the message. var userText = body + "<br><br><b>" + name; var myTextNode = $("#base").clone(); myTextNode.text(userText); var image_url; var n = name.localeCompare("Scott"); if (n == 0) image_url = "./images/av1.png"; else image_url = "./images/av2.png"; var images_div = '<img src="' + image_url + '" alt="Avatar" class="right" style=""width:100%;"">'; myTextNode.html(userText); myTextNode.append(images_div); // Add the message to the GUI. $("#messages").append(myTextNode); } } catch (err) { console.log("Error loading messages: ", err); } } catch (err) { console.log("Error retrieving SQS queue URL: ", err); } };

推送訊息

用戶選擇他們的名稱並輸入他們的消息,並提交啟動函數的消息。pushMessage pushMessage擷取 Amazon SQS 佇列網址,然後傳送訊息文字具有唯一訊息 ID 值 (GUID) 的訊息,並將使用者傳送至 Amazon SQS 佇列。然後,它會從 Amazon SQS 佇列擷取所有訊息並加以顯示。

const pushMessage = async () => { // Get and convert user and message input. var user = $("#username").val(); var message = $("#textarea").val(); // Create random deduplication ID. var dt = new Date().getTime(); var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function ( c ) { var r = (dt + Math.random() * 16) % 16 | 0; dt = Math.floor(dt / 16); return (c == "x" ? r : (r & 0x3) | 0x8).toString(16); }); try { // Set the Amazon SQS Queue parameters. const queueParams = { QueueName: QueueName, Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }; const data = await sqsClient.send(new GetQueueUrlCommand(queueParams)); console.log("Success. The URL of the SQS Queue is: ", data.QueueUrl); // Set the parameters for the message. var messageParams = { MessageAttributes: { Name: { DataType: "String", StringValue: user, }, }, MessageBody: message, MessageDeduplicationId: uuid, MessageGroupId: "GroupA", QueueUrl: data.QueueUrl, }; const result = await sqsClient.send(new SendMessageCommand(messageParams)); console.log("Success", result.MessageId); // Set the parameters for retrieving all messages in the SQS queue. var getMessageParams = { QueueUrl: data.QueueUrl, MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], VisibilityTimeout: 20, WaitTimeSeconds: 20, }; // Retrieve messages from SQS Queue. const final = await sqsClient.send( new ReceiveMessageCommand(getMessageParams) ); console.log("Successfully retrieved", final.Messages); $("#messages").empty(); // Loop through messages for user and message body. var i; for (i = 0; i < final.Messages.length; i++) { const name = final.Messages[i].MessageAttributes.Name.StringValue; const body = final.Messages[i].Body; // Create the HTML for the message. var userText = body + "<br><br><b>" + name; var myTextNode = $("#base").clone(); myTextNode.text(userText); var image_url; var n = name.localeCompare("Scott"); if (n == 0) image_url = "./images/av1.png"; else image_url = "./images/av2.png"; var images_div = '<img src="' + image_url + '" alt="Avatar" class="right" style=""width:100%;"">'; myTextNode.html(userText); myTextNode.append(images_div); // Add the HTML to the GUI. $("#messages").append(myTextNode); } } catch (err) { console.log("Error", err); } }; // Make the function available to the browser window. window.pushMessage = pushMessage;

清除訊息

purge從 Amazon SQS 佇列和使用者介面刪除訊息。

// Delete the message from the Amazon SQS queue. const purge = async () => { try { // Set the Amazon SQS Queue parameters. const queueParams = { QueueName: QueueName, Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }; // Get the Amazon SQS Queue URL. const data = await sqsClient.send(new GetQueueUrlCommand(queueParams)); console.log("Success", data.QueueUrl); // Delete all the messages in the Amazon SQS Queue. const result = await sqsClient.send( new PurgeQueueCommand({ QueueUrl: data.QueueUrl }) ); // Delete all the messages from the GUI. $("#messages").empty(); console.log("Success. All messages deleted.", data); } catch (err) { console.log("Error", err); } }; // Make the function available to the browser window. window.purge = purge;

捆綁 JavaScript

這個 comlete 瀏覽器腳本代碼可在這裡找到。 GitHub 。

現在使用 webpack 將index.js和AWS SDK for JavaScript模塊捆綁到一個文件中main.js

  1. 如果您還沒有,請按照此示例中必要條件的安裝 webpack。

    注意

    如需 Webpack 的相關資訊,請參閱捆綁應用程序與網絡包

  2. 在命令列中執行下列命令,將此範例的 JavaScript 內容捆綁到名為的檔案中<index.js>

    webpack index.js --mode development --target web --devtool false -o main.js

後續步驟

恭喜您!您已建立並部署使用 Amazon SQS 的AWS簡訊應用程式。正如本教程開頭所述,請務必終止所有您創建的資源,同時通過本教程,以確保你不再收取他們的費用。您可以透過刪除您在本教學課程建立資AWS源 主題中建立的AWS CloudFormation堆疊來執行此操作,如下所示:

  1. AWS管理主控台AWS CloudFormation中開啟。

  2. 開啟「堆疊」頁面,然後選取堆疊。

  3. 選擇刪除