创建示例消息收发应用程序 - Amazon SDK for JavaScript
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

Amazon SDK for JavaScript V3 API 参考指南详细描述了 Amazon SDK for JavaScript 版本 3 (V3) 的所有 API 操作。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

创建示例消息收发应用程序

您可以使用 Amazon SDK for JavaScript 和 Amazon Simple Queue Service (Amazon SQS) 创建用于发送和检索消息的 Amazon 应用程序。消息存储在先进先出 (FIFO) 队列中,该队列可确保消息的顺序一致。例如,存储在队列中的第一条消息是从队列中读取的第一条消息。

注意

有关 Amazon SQS 的更多信息,请参阅什么是 Amazon Simple Queue Service?

在本教程中,您将创建一个名为 Amazon Messaging 的 Node.js 应用程序。

完成费用:本文档中包含的 Amazon 服务包含在 Amazon 免费套餐中。

注意:在学习本教程时,请务必终止您创建的所有资源,以确保系统不会向您收费。

先决条件

要设置和运行此示例,您必须先完成以下任务:

  • 设置项目环境以运行这些 Node TypeScript 示例,并安装所需的模块Amazon SDK for JavaScript和第三方模块。按照上的说明进行操作 GitHub

  • 使用用户凭证创建共享配置文件。有关提供共享凭证文件的更多信息,请参阅《Amazon SDK 和工具参考指南》中的共享配置和凭证文件

重要

此示例使用 ECMAScript6 (ES6)。这需要使用 Node.js 版本 13.x 或更高版本。要下载并安装最新版本的 Node.js,请参阅 Node.js 下载

但是,如果您更喜欢使用 CommonJS 语法,请参阅 JavaScript ES6/CommonJS 语法

创建 Amazon 资源

本教程要求具有以下资源。

  • 一个未经身份验证的 IAM 角色,具有 Amazon SQS 权限。

  • 一个名为 Message.fifo 的 FIFO Amazon SQS 队列 - 有关创建队列的信息,请参阅创建 Amazon SQS 队列

您可以手动创建这些资源,但我们建议使用本教程中所述的 Amazon CloudFormation (Amazon CloudFormation) 预置这些资源。

注意

Amazon CloudFormation 是一个软件开发框架,使您能够定义云应用程序资源。有关更多信息,请参阅 Amazon CloudFormation 用户指南

使用 Amazon CloudFormation 创建 Amazon 资源

Amazon CloudFormation 让您能够以可预测、可重复的方式创建和预置 Amazon 基础设施部署。有关 Amazon CloudFormation 的更多信息,请参阅 Amazon CloudFormation 用户指南

使用 Amazon CLI 创建 Amazon CloudFormation 堆栈:

  1. 按照 Amazon CLI 用户指南中的说明安装和配置 Amazon CLI。

  2. 在项目文件夹的根目录setup.yaml中创建一个名为的文件,然后将此处的内容复制 GitHub到该文件中。

    注意

    该Amazon CloudFormation模板是使用此处Amazon CDK提供的模板生成的 GitHub。有关 Amazon CDK 的更多信息,请参阅 Amazon Cloud Development Kit (Amazon CDK) 开发人员指南

  3. 从命令行运行以下命令,将 STACK_NAME 替换为堆栈的唯一名称。

    重要

    在一个 Amazon 区域和一个 Amazon 账户中,堆栈名称必须唯一。您最多可指定 128 个字符,支持数字和连字符。

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

    有关 create-stack 命令参数的更多信息,请参阅 Amazon CLI 命令参考指南Amazon CloudFormation 用户指南

    要查看创建的资源,请在 Amazon 管理控制台中打开 Amazon CloudFormation,选择堆栈,然后选择资源选项卡。

了解 Amazon 消息收发应用程序

要向 SQS 队列发送消息,请将消息输入到应用程序中并选择“发送”。

发送消息后,应用程序会显示该消息。

您可以选择清除,从 Amazon SQS 队列中清除消息。这会导致队列为空,并且应用程序中不会显示任何消息。

以下内容描述了应用程序处理消息的方式:

  • 用户选择自己的名字并输入消息,然后提交消息,这将启动 pushMessage 函数。

  • pushMessage 检索 Amazon SQS 队列 URL,然后向 Amazon SQS 队列发送一条带有唯一消息 ID 值 (GUID)、消息文本和用户的消息。

  • pushMessage 从 Amazon SQS 队列中检索消息,提取每条消息的用户和消息,然后显示消息。

  • 用户可以清除消息,从而将消息从 Amazon SQS 队列和用户界面中删除。

创建 HTML 页面

现在,您可以创建应用程序的图形用户界面 (GUI) 所需的 HTML 文件。创建一个名为 index.html的文件。将以下代码复制并粘贴到 index.html。此 HTML 引用 main.js。这是 index.js 的捆绑版本,其中包含所需的 Amazon 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 客户端对象。替换每个对象中的 REGIONIDENTITY_POOL_ID

注意

使用您在创建 Amazon 资源 中创建的 Amazon Cognito 身份池的 ID。

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 中,导入所需的 Amazon SDK for JavaScript 模块和命令。将 SQS_QUEUE_NAME 替换为您在创建 Amazon 资源 中创建的 Amazon SQS 队列的名称。

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

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 队列 URL,然后向 Amazon SQS 队列发送一条带有唯一消息 ID 值 (GUID)、消息文本和用户的消息。然后,它会从 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

此完整的浏览器脚本代码可从此处获得。 GitHub 。

现在使用 Webpack 将 index.js 和 Amazon SDK for JavaScript 模块捆绑到一个文件 main.js 中。

  1. 如果您尚未安装 Webpack,请按照本示例中的先决条件部分进行安装。

    注意

    有关 webpack 的信息,请参阅将应用程序与 webpack 捆绑在一起

  2. 在命令行中运行以下命令,将本示例的捆绑到名 JavaScript 为的文件中<index.js>

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

后续步骤

恭喜您!您已经创建并部署了使用 Amazon SQS 的 Amazon 消息收发应用程序。如本教程开头所述,请务必在学习本教程时终止您创建的所有资源,以确保系统不再向您收费。您可以通过删除在本教程的创建 Amazon 资源 主题中创建的 Amazon CloudFormation 堆栈来实现此目的,方法如下所示:

  1. 打开 Amazon 管理控制台中的 Amazon CloudFormation

  2. 打开堆栈页面,然后选择堆栈。

  3. 选择删除