设置 Amazon SQS 队列属性 - AWS SDK 代码示例

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

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

设置 Amazon SQS 队列属性

以下代码示例演示如何设置 Amazon SQS 队列的属性。

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
AWS SDK for .NET
注意

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

为主题设置队列的策略属性。

/// <summary> /// Set the policy attribute of a queue for a topic. /// </summary> /// <param name="queueArn">The ARN of the queue.</param> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="queueUrl">The url for the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> SetQueuePolicyForTopic(string queueArn, string topicArn, string queueUrl) { var queuePolicy = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Effect\": \"Allow\"," + "\"Principal\": {" + $"\"Service\": " + "\"sns.amazonaws.com\"" + "}," + "\"Action\": \"sqs:SendMessage\"," + $"\"Resource\": \"{queueArn}\"," + "\"Condition\": {" + "\"ArnEquals\": {" + $"\"aws:SourceArn\": \"{topicArn}\"" + "}" + "}" + "}]" + "}"; var attributesResponse = await _amazonSQSClient.SetQueueAttributesAsync( new SetQueueAttributesRequest() { QueueUrl = queueUrl, Attributes = new Dictionary<string, string>() { { "Policy", queuePolicy } } }); return attributesResponse.HttpStatusCode == HttpStatusCode.OK; }
  • 有关 API 的详细信息,请参阅 AWS SDK for .NETAPI 参考SetQueueAttributes中的。

C++
适用于 C++ 的 SDK
注意

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

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Set the value for an attribute in an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param attributeName: An attribute name enum. \param attribute: The attribute value as a string. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::setQueueAttributes(const Aws::String &queueURL, Aws::SQS::Model::QueueAttributeName attributeName, const Aws::String &attribute, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributes( attributeName, attribute); const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes( request); if (outcome.IsSuccess()) { std::cout << "Successfully set the attribute " << Aws::SQS::Model::QueueAttributeNameMapper::GetNameForQueueAttributeName( attributeName) << " with value " << attribute << " in queue " << queueURL << "." << std::endl; } else { std::cout << "Error setting attribute for queue " << queueURL << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • 有关 API 的详细信息,请参阅 AWS SDK for C++API 参考SetQueueAttributes中的。

CLI
AWS CLI

设置队列属性

此示例将指定队列的传输延迟设置为 10 秒,最大消息大小为 128 KB(128 KB * 1,024 字节),消息保留期为 3 天(3 天 * 24 小时 * 60 分钟 * 60 秒),接收消息等待时间为 20 秒,默认可见性超时为 60 秒。此示例还将指定的死信队列与最大接收数 1,000 条消息相关联。

命令:

aws sqs set-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyNewQueue --attributes file://set-queue-attributes.json

输入文件 (set-queue-attributes.json):

{ "DelaySeconds": "10", "MaximumMessageSize": "131072", "MessageRetentionPeriod": "259200", "ReceiveMessageWaitTimeSeconds": "20", "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:80398EXAMPLE:MyDeadLetterQueue\",\"maxReceiveCount\":\"1000\"}", "VisibilityTimeout": "60" }

输出:

None.
Go
适用于 Go V2 的 SDK
注意

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

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // AttachSendMessagePolicy uses the SetQueueAttributes action to attach a policy to an // Amazon SQS queue that allows the specified Amazon SNS topic to send messages to the // queue. func (actor SqsActions) AttachSendMessagePolicy(queueUrl string, queueArn string, topicArn string) error { policyDoc := PolicyDocument{ Version: "2012-10-17", Statement: []PolicyStatement{{ Effect: "Allow", Action: "sqs:SendMessage", Principal: map[string]string{"Service": "sns.amazonaws.com"}, Resource: aws.String(queueArn), Condition: PolicyCondition{"ArnEquals": map[string]string{"aws:SourceArn": topicArn}}, }}, } policyBytes, err := json.Marshal(policyDoc) if err != nil { log.Printf("Couldn't create policy document. Here's why: %v\n", err) return err } _, err = actor.SqsClient.SetQueueAttributes(context.TODO(), &sqs.SetQueueAttributesInput{ Attributes: map[string]string{ string(types.QueueAttributeNamePolicy): string(policyBytes), }, QueueUrl: aws.String(queueUrl), }) if err != nil { log.Printf("Couldn't set send message policy on queue %v. Here's why: %v\n", queueUrl, err) } return err } // PolicyDocument defines a policy document as a Go struct that can be serialized // to JSON. type PolicyDocument struct { Version string Statement []PolicyStatement } // PolicyStatement defines a statement in a policy document. type PolicyStatement struct { Effect string Action string Principal map[string]string `json:",omitempty"` Resource *string `json:",omitempty"` Condition PolicyCondition `json:",omitempty"` } // PolicyCondition defines a condition in a policy. type PolicyCondition map[string]map[string]string
  • 有关 API 的详细信息,请参阅 AWS SDK for GoAPI 参考SetQueueAttributes中的。

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

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

import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue-url"; export const main = async (queueUrl = SQS_QUEUE_URL) => { const command = new SetQueueAttributesCommand({ QueueUrl: queueUrl, Attributes: { DelaySeconds: "1", }, }); const response = await client.send(command); console.log(response); return response; };

将 Amazon SQS 队列配置为使用长轮询。

import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; export const main = async (queueUrl = SQS_QUEUE_URL) => { const command = new SetQueueAttributesCommand({ Attributes: { ReceiveMessageWaitTimeSeconds: "20", }, QueueUrl: queueUrl, }); const response = await client.send(command); console.log(response); return response; };
  • 有关 API 的详细信息,请参阅 AWS SDK for JavaScriptAPI 参考SetQueueAttributes中的。