示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载本文以aws-doc-sdk-examples仓库中的 javascriptv3/example_code/sns/README.md 为主体系统讲解如何用 AWS SDK for JavaScript (v3) 对接 Amazon Simple Notification ServiceAmazon SNS覆盖从客户端初始化、主题创建/删除、多协议订阅到短信与队列消息发布的完整操作链并深入到 Hello 入门示例与发布消息到队列场景的源码实现。读完本文你将掌握基于 SDK v3 的 SNS 全套单操作调用方式、分页遍历技巧、过滤订阅配置与集成测试方法可直接照搬到自己的 Node.js 项目中。Amazon SNS 与 SDK v3 概览Amazon SNS 是一项云原生消息通知服务让应用程序、终端用户和设备能够即时发送与接收来自云端的事件通知。它的核心抽象是主题Topic——一个逻辑上的发布/订阅通道发布者向主题推送消息订阅者HTTP/S 端点、邮箱、Lambda 函数、SQS 队列、SMS 手机号、移动端应用等通过订阅关系实时接收。在aws-doc-sdk-examples仓库中JavaScript 侧的 SNS 示例统一位于 javascriptv3/example_code/sns 目录全部基于 ECMAScript 6ES6模块语法编写。目录内代码分为三层组织目录/文件职责libs/snsClient.js全局复用的SNSClient客户端实例actions/17 个单操作示例对应一个服务 API 调用tests/11 个 Vitest 集成测试用例hello.js入门示例分页列出账户下所有 SNS 主题从 package.json 可见示例依赖aws-sdk/client-sns^3.370.0测试阶段额外使用aws-sdk/client-sqs与vitest并通过type: module声明整个包采用 ES 模块体系。环境准备SDK v3 前置条件与客户端初始化前置条件运行本目录任何示例前需要先完成 javascriptv3 根 README 中列出的前置准备主要包括Node.js 运行时与 npm 包管理器AWS 账户及具备 SNS 最小权限的 IAM 凭证建议遵循 least privilege 最小权限原则在javascriptv3目录完成依赖安装示例以 workspace 形式统一管理 node_modules。共享客户端libs/snsClient.js目录下几乎所有actions/示例都复用同一个客户端实例它位于 libs/snsClient.jsimport { SNSClient } from aws-sdk/client-sns; // The AWS Region can be provided here using the region property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient new SNSClient({});这里有两个关键点region可选构造时传入空配置对象即可。SDK v3 遵循共享凭证/配置解析链自动从环境变量、共享凭证文件、AWS config 文件等位置读取区域与凭证一处定义、处处复用后续每个 action 文件通过import { snsClient } from ../libs/snsClient.js引入避免重复创建客户端、复用连接池。Hello Amazon SNS分页遍历 ListTopics入门示例 hello.js 展示了 SDK v3 推荐的分页写法——使用命令构造器自带的paginateListTopics分页迭代器而非手动管理NextTokenimport { fileURLToPath } from node:url; import { SNSClient, paginateListTopics } from aws-sdk/client-sns; export const helloSns async () { // The configuration object ({}) is required. If the region and credentials // are omitted, the SDK uses your local configuration if it exists. const client new SNSClient({}); // You can also use ListTopicsCommand, but to use that command you must // handle the pagination yourself. You can do that by sending the ListTopicsCommand // with the NextToken parameter from the previous request. const paginatedTopics paginateListTopics({ client }, {}); const topics []; for await (const page of paginatedTopics) { if (page.Topics?.length) { topics.push(...page.Topics); } } const suffix topics.length 1 ? : s; console.log( Hello, Amazon SNS! You have ${topics.length} topic${suffix} in your account., ); console.log(topics.map((t) * ${t.TopicArn}).join(\n)); }; // Invoke main function if this file was run directly. if (process.argv[1] fileURLToPath(import.meta.url)) { helloSns(); }值得留意的是源码注释中明确的两种等价方案直接发送ListTopicsCommand时需要开发者自行以NextToken循环翻页而paginateListTopics用for await...of语法对开发者完全屏蔽了这一细节。脚本末尾通过fileURLToPath(import.meta.url)判断是否被直接执行保证同一个文件既可以作为模块被导入也可以node ./hello.js直接运行。运行方式node ./hello.js预期输出类似Hello, Amazon SNS! You have 2 topics in your account. * arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic单操作示例详解主题生命周期README 的 Single actions 清单列出了 13 个服务 API。这里结合源码逐一展开其中最核心的调用链。创建主题CreateTopicactions/create-topic.js 演示了主题创建返回的响应中带有新主题的 ARNimport { CreateTopicCommand } from aws-sdk/client-sns; import { snsClient } from ../libs/snsClient.js; export const createTopic async (topicName TOPIC_NAME) { const response await snsClient.send( new CreateTopicCommand({ Name: topicName }), ); console.log(response); // { // $metadata: { httpStatusCode: 200, requestId: 087b8ad2-4593-50c4-a496-d7e90b82cf3e, ... }, // TopicArn: arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME // } return response; };参数只有一个Name主题名。创建标准主题时名称仅需满足 SNS 命名规则字母、数字、连字符与下划线若需创建FIFO 主题可在Attributes中设置FifoTopic: true并追加.fifo后缀的命名详见下方场景章节响应中的TopicArn是后续所有订阅、发布、删除操作的身份标识。列出主题ListTopicsactions/list-topics.js 直接发送ListTopicsCommand({})export const listTopics async () { const response await snsClient.send(new ListTopicsCommand({})); console.log(response); // { // $metadata: { httpStatusCode: 200, requestId: 936bc5ad-83ca-53c2-b0b7-9891167b909e, ... }, // Topics: [ { TopicArn: arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic } ] // } return response; };注意ListTopicsCommand默认按页返回Topics数组账户主题较多时应优先使用 Hello 示例中的paginateListTopics分页迭代器。删除主题DeleteTopicactions/delete-topic.js 只需传入待删除主题的 ARNimport { DeleteTopicCommand } from aws-sdk/client-sns; import { snsClient } from ../libs/snsClient.js; export const deleteTopic async (topicArn TOPIC_ARN) { const response await snsClient.send( new DeleteTopicCommand({ TopicArn: topicArn }), ); // 成功时仅返回 $metadatahttpStatusCode: 200 };查询与修改主题属性actions/get-topic-attributes.jsGetTopicAttributesCommand返回主题的完整属性集策略、订阅数、消息保留时长等actions/set-topic-attributes.jsSetTopicAttributesCommand用于修改显示名DisplayName、交付策略等属性。单操作示例详解订阅管理订阅多协议 Subscribeactions/subscribe-email.js 演示最常见的邮箱订阅import { SubscribeCommand } from aws-sdk/client-sns; import { snsClient } from ../libs/snsClient.js; export const subscribeEmail async ( topicArn TOPIC_ARN, emailAddress usernme.com, ) { const response await snsClient.send( new SubscribeCommand({ Protocol: email, TopicArn: topicArn, Endpoint: emailAddress, }), ); // 响应中的 SubscriptionArn 为 pending confirmation待确认状态 };SubscribeCommand的关键参数是Protocol与Endpoint的组合目录内覆盖了多种协议示例文件ProtocolEndpoint 说明subscribe-email.jsemail订阅者邮箱subscribe-app.js移动应用平台平台终端 ARNsubscribe-lambda.jslambdaLambda 函数 ARNsubscribe-queue.jssqsSQS 队列 ARNsubscribe-queue-filtered.jssqsSQS 队列 ARN 订阅过滤器以 subscribe-queue.js 为例SQS 订阅的调用非常直接import { SubscribeCommand, SNSClient } from aws-sdk/client-sns; const client new SNSClient({}); export const subscribeQueue async ( topicArn TOPIC_ARN, queueArn QUEUE_ARN, ) { const command new SubscribeCommand({ TopicArn: topicArn, Protocol: sqs, Endpoint: queueArn, }); const response await client.send(command); // 成功时 SubscriptionArn 为 arn:aws:sns:us-east-1:...:subscribe-queue-test-430895:xxxxxxxx-... return response; };带过滤策略的订阅FilterPolicysubscribe-queue-filtered.js 展示了 SNS消息过滤能力——通过Attributes传入FilterPolicy与FilterPolicyScope让订阅只接收满足条件的事件export const subscribeQueueFiltered async ( topicArn TOPIC_ARN, queueArn QUEUE_ARN, ) { const command new SubscribeCommand({ TopicArn: topicArn, Protocol: sqs, Endpoint: queueArn, Attributes: { // This subscription will only receive messages with the event attribute set to order_placed. FilterPolicyScope: MessageAttributes, FilterPolicy: JSON.stringify({ event: [order_placed], }), }, }); const response await client.send(command); return response; };要点说明FilterPolicyScope取MessageAttributes表示过滤依据是发布消息时携带的消息属性Message AttributesFilterPolicy是 JSON 序列化字符串{ event: [order_placed] }表示仅当消息的event属性值命中order_placed时才投递该机制与下方发布消息到队列场景配套使用发布者先SetSMSAttributes/消息属性订阅队列即可按事件类型选择性接收。确认订阅与退订actions/confirm-subscription.js 使用ConfirmSubscriptionCommand。源码注释明确指出只有非 AWS 服务的端点HTTP/S、邮箱或跨账户订阅才需要显式确认SQS、Lambda 等 AWS 服务端点无需此步。命令携带Token订阅确认令牌与AuthenticateOnUnsubscribe设为false表示允许匿名退订export const confirmSubscription async ( token TOKEN, topicArn TOPIC_ARN, ) { const response await snsClient.send( new ConfirmSubscriptionCommand({ Token: token, TopicArn: topicArn, // If this is true, the subscriber cannot unsubscribe while unauthenticated. AuthenticateOnUnsubscribe: false, }), ); return response; };actions/unsubscribe.jsUnsubscribeCommand传入订阅 ARN 解除订阅关系actions/list-subscriptions-by-topic.jsListSubscriptionsByTopicCommand按主题列出全部订阅者同样支持分页参数。单操作示例详解消息发布与短信向主题发布消息Publishactions/publish-topic.js 通过PublishCommand向主题推送消息import { PublishCommand } from aws-sdk/client-sns; import { snsClient } from ../libs/snsClient.js; export const publish async ( message Hello from SNS!, topicArn TOPIC_ARN, ) { const response await snsClient.send( new PublishCommand({ Message: message, TopicArn: topicArn, }), ); // 响应中包含 MessageId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx return response; };Message既可以是普通字符串也可以是对象——当使用json类型的MessageStructure时对象会被按协议分别投递即多协议消息分发若想结合上面订阅的过滤策略可在命令中补充MessageAttributes让过滤器据此匹配。发送短信Publish 到 PhoneNumberactions/publish-sms.js 展示了 SMS 用法。源码注释特意强调了一个约束PhoneNumber、TopicArn、TargetArn三者必须且只能指定一个export const publish async ( message Hello from SNS!, phoneNumber 15555555555, ) { const response await snsClient.send( new PublishCommand({ Message: message, // One of PhoneNumber, TopicArn, or TargetArn must be specified. PhoneNumber: phoneNumber, }), ); return response; };短信属性管理GetSMSAttributes / SetSMSAttributesactions/get-sms-attributes.jsGetSMSAttributesCommand读取账户级 SMS 属性如每月发送限额、默认短信类型、发送者 IDactions/set-sms-attribute-type.jsSetSMSAttributesCommand可配置DefaultSMSTypePromotional/Transactional等参数控制短信的发送策略与限额。其他单操作README 清单中剩余的操作分布在对应 action 文件中actions/confirm-subscription.jsConfirmSubscription见上文actions/list-topics.jsListTopics对CheckIfPhoneNumberIsOptedOut查询号码是否已退订短信等操作的封装同样位于actions/下对应文件。场景示例发布消息到队列Topics QueuesREADME 的场景章节指向跨服务示例 cross-services/wkflw-topics-queues/index.js它串联起 SNS 与 SQS 的典型工作流覆盖四步能力创建主题FIFO 或非 FIFO通过CreateTopicCommand创建标准主题FIFO 主题则需设置FifoTopic属性并以.fifo结尾命名订阅多个队列到主题可选过滤对多个 SQS 队列执行SubscribeCommandProtocol: sqs可叠加本文所述的FilterPolicy过滤策略实现按消息属性路由向主题发布消息通过PublishCommand发布消息使所有符合条件的订阅队列收到副本轮询队列接收消息使用 SQS 客户端ReceiveMessage拉取各队列实际收到的消息验证投递与过滤结果。该场景在 README 中同时给出配套的custom.scenario_prereqs与custom.scenarios占位区块说明在官方文档的代码示例体系中场景代码还配有针对 SQS 的预置说明仓库内 tests/ 下的subscribe-queue.integration.test.js等集成测试即为该场景的自动化验证实现。运行与调试指南运行单个操作README 给出的标准命令格式为node ./actions/fileName例如node ./actions/create-topic.js node ./actions/publish-topic.js node ./actions/subscribe-email.js每个 action 文件都遵循直接运行时自动调用导出函数的模式if (process.argv[1] fileURLToPath(import.meta.url))因此无需额外入口即可执行也可以import其导出的异步函数嵌入自己的业务代码。运行场景node ./scenarios/fileName场景脚本通常依赖多个服务与资源如 SQS 队列运行前请确认对应前置条件。命令行选项部分 action 与场景支持从命令行传入选项node ./scenarios/fileName --option1 --option2选项解析基于 Node.js 内置的 util.parseArgs不同脚本的可用选项需查看对应文件中的parseArgs配置。ES6 与 CommonJS 兼容所有示例均以 ECMAScript 6ES6编写import/export语法。如需转换为 CommonJSrequire/module.exports可参考 SDK for JavaScript (v3) 开发指南中的语法说明。集成测试本目录通过 Vitest 提供 11 个集成测试文件位于 tests/覆盖主题操作create-delete-topic.integration.test.js、list-topics.integration.test.js、get-topic-attributes.integration.test.js、set-topic-attributes.integration.test.js订阅操作subscribe.integration.test.js、subscribe-queue.integration.test.js、list-subscriptions-by-topic.integration.test.js、confirm-subscription.integration.test.js消息发布与短信publish.integration.test.js、get-sms-attributes.integration.test.js、set-sms-attribute-type.integration.test.js。package.json 中预置了测试命令执行时会调用 vitest 并以 JUnit 格式输出测试报告npm run integration-test⚠️ 集成测试会真实调用 AWS 服务运行测试同样可能产生 AWS 账户费用。完整的测试运行说明见 javascriptv3 根 README 的 Tests 章节。注意事项与最佳实践费用提醒运行示例与测试都会产生真实的 AWS 资源调用可能带来账户费用建议优先使用 AWS 免费套餐范围内的小规模资源最小权限原则为运行代码的 IAM 角色/用户仅授予完成任务所需的最小权限如sns:CreateTopic、sns:Publish、sns:Subscribe不要直接附加管理员策略区域可用性SNS 服务与示例代码并非在所有 AWS 区域经过完整测试生产部署前应确认目标区域的服务可用性与 SDK 版本兼容性FIFO 主题命名约束FIFO 主题名必须以.fifo结尾且发布端与订阅端都必须严格遵循 FIFO 的消息去重与顺序语义过滤策略为 JSON 字符串FilterPolicy必须以JSON.stringify序列化后传入Attributes否则订阅请求会被拒绝订阅确认规则只有 HTTP/S、邮箱等非 AWS 服务端点才需要执行ConfirmSubscriptionSQS/Lambda 订阅无需确认。参考资源javascriptv3/example_code/sns/README.md本文所依据的官方示例说明javascriptv3 根 README包含全局前置条件与测试运行说明libs/snsClient.jsSDK v3 客户端初始化范式hello.js分页 API 的标准用法cross-services/wkflw-topics-queues/index.jsSNS SQS 跨服务场景tests/可复用的集成测试示例。Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.SPDX-License-Identifier: Apache-2.0赞分享示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载相关推荐使用 AWS SDK for C 操作 Amazon SNS从 Hello World 到发布/订阅的完整代码示例实战指南使用 AWS SDK for C 操作 Amazon SNS从 Hello World 到发布/订阅的完整代码示例实战指南 Amazon Simple N示例工程教程后端Wazuh 从 OSquery 迁移到 IT HygieneSyscollector 原生资产清点迁移指南Wazuh 从 OSquery 迁移到 IT HygieneSyscollector 原生资产清点迁移指南 本指南面向仍在 Wazuh 4.x 中使用 OSq示例工程教程后端Linux 内核 BPF_PROG_RUN 详解从用户态执行 eBPF 程序、无副作用测试与 XDP 活帧Live Frames模式Linux 内核 BPF_PROG_RUN 详解从用户态执行 eBPF 程序、无副作用测试与 XDP 活帧Live Frames模式 本文围绕 Linux示例工程教程后端上一篇Jellyfin-Kodi媒体中心革命从零开始的智能观影体验下一篇Cursor Pro无限额度技术指南深入解析机器码重置与自动化解决方案创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考