使用软件开发工具包的 Amazon SQS 的代码示例 AWS - AWS SDK 代码示例

文档 AWS SDK 示例 GitHub 存储库中还有更多 S AWS DK 示例

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

使用软件开发工具包的 Amazon SQS 的代码示例 AWS

以下代码示例向您展示了如何将亚马逊简单队列服务 (Amazon SQS) 与软件开发套件 (SDK) 配合 AWS 使用。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是展示如何通过在同一服务中调用多个函数来完成特定任务任务的代码示例。

跨服务示例 是指跨多个 AWS 服务工作的示例应用程序。

更多资源

开始使用

以下代码示例展示了如何开始使用 Amazon SQS。

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using Amazon.SQS; using Amazon.SQS.Model; namespace SQSActions; public static class HelloSQS { static async Task Main(string[] args) { var sqsClient = new AmazonSQSClient(); Console.WriteLine($"Hello Amazon SQS! Following are some of your queues:"); Console.WriteLine(); // You can use await and any of the async methods to get a response. // Let's get the first five queues. var response = await sqsClient.ListQueuesAsync( new ListQueuesRequest() { MaxResults = 5 }); foreach (var queue in response.QueueUrls) { Console.WriteLine($"\tQueue Url: {queue}"); Console.WriteLine(); } } }
  • 有关 API 的详细信息,请参阅 AWS SDK for .NET API 参考ListQueues中的。

C++
SDK for C++
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

C MakeLists .txt cMake 文件的代码。

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS sqs) # Set this project's name. project("hello_sqs") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if(WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif() add_executable(${PROJECT_NAME} hello_sqs.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

hello_sqs.cpp 源文件的代码。

#include <aws/core/Aws.h> #include <aws/sqs/SQSClient.h> #include <aws/sqs/model/ListQueuesRequest.h> #include <iostream> /* * A "Hello SQS" starter application that initializes an Amazon Simple Queue Service * (Amazon SQS) client and lists the SQS queues in the current account. * * main function * * Usage: 'hello_sqs' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SQS::SQSClient sqsClient(clientConfig); Aws::Vector<Aws::String> allQueueUrls; Aws::String nextToken; // Next token is used to handle a paginated response. do { Aws::SQS::Model::ListQueuesRequest request; Aws::SQS::Model::ListQueuesOutcome outcome = sqsClient.ListQueues(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::String> &pageOfQueueUrls = outcome.GetResult().GetQueueUrls(); if (!pageOfQueueUrls.empty()) { allQueueUrls.insert(allQueueUrls.cend(), pageOfQueueUrls.cbegin(), pageOfQueueUrls.cend()); } } else { std::cerr << "Error with SQS::ListQueues. " << outcome.GetError().GetMessage() << std::endl; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); std::cout << "Hello Amazon SQS! You have " << allQueueUrls.size() << " queue" << (allQueueUrls.size() == 1 ? "" : "s") << " in your account." << std::endl; if (!allQueueUrls.empty()) { std::cout << "Here are your queue URLs." << std::endl; for (const Aws::String &queueUrl: allQueueUrls) { std::cout << " * " << queueUrl << std::endl; } } } Aws::ShutdownAPI(options); // Should only be called once. return 0; }
  • 有关 API 的详细信息,请参阅 AWS SDK for C++ API 参考ListQueues中的。

Go
适用于 Go V2 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Queue Service // (Amazon SQS) client and list the queues in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } sqsClient := sqs.NewFromConfig(sdkConfig) fmt.Println("Let's list the queues for your account.") var queueUrls []string paginator := sqs.NewListQueuesPaginator(sqsClient, &sqs.ListQueuesInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(context.TODO()) if err != nil { log.Printf("Couldn't get queues. Here's why: %v\n", err) break } else { queueUrls = append(queueUrls, output.QueueUrls...) } } if len(queueUrls) == 0 { fmt.Println("You don't have any queues!") } else { for _, queueUrl := range queueUrls { fmt.Printf("\t%v\n", queueUrl) } } }
  • 有关 API 的详细信息,请参阅 AWS SDK for Go API 参考ListQueues中的。

Java
适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.SqsException; import software.amazon.awssdk.services.sqs.paginators.ListQueuesIterable; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class HelloSQS { public static void main(String[] args) { SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); listQueues(sqsClient); sqsClient.close(); } public static void listQueues(SqsClient sqsClient) { try { ListQueuesIterable listQueues = sqsClient.listQueuesPaginator(); listQueues.stream() .flatMap(r -> r.queueUrls().stream()) .forEach(content -> System.out.println(" Queue URL: " + content.toLowerCase())); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关 API 的详细信息,请参阅 AWS SDK for Java 2.x API 参考ListQueues中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

初始化 Amazon SQS 客户端并列出队列。

import { SQSClient, paginateListQueues } from "@aws-sdk/client-sqs"; export const helloSqs = 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 SQSClient({}); // You can also use `ListQueuesCommand`, but to use that command you must // handle the pagination yourself. You can do that by sending the `ListQueuesCommand` // with the `NextToken` parameter from the previous request. const paginatedQueues = paginateListQueues({ client }, {}); const queues = []; for await (const page of paginatedQueues) { if (page.QueueUrls?.length) { queues.push(...page.QueueUrls); } } const suffix = queues.length === 1 ? "" : "s"; console.log( `Hello, Amazon SQS! You have ${queues.length} queue${suffix} in your account.`, ); console.log(queues.map((t) => ` * ${t}`).join("\n")); };
  • 有关 API 的详细信息,请参阅 AWS SDK for JavaScript API 参考ListQueues中的。

Kotlin
适用于 Kotlin 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

package com.kotlin.sqs import aws.sdk.kotlin.services.sqs.SqsClient import aws.sdk.kotlin.services.sqs.paginators.listQueuesPaginated import kotlinx.coroutines.flow.transform suspend fun main() { listTopicsPag() } suspend fun listTopicsPag() { SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient .listQueuesPaginated { } .transform { it.queueUrls?.forEach { queue -> emit(queue) } } .collect { queue -> println("The Queue URL is $queue") } } }
  • 有关 API 的详细信息,请参阅适用ListQueues于 K otlin 的AWS SDK API 参考