SetQueueAttributes 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

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

SetQueueAttributes 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 SetQueueAttributes

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on 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; }
C++
C++ 的 SDK
注意

還有更多 on 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(); }

設定無效信件佇列。

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Connect an Amazon Simple Queue Service (Amazon SQS) queue to an associated //! dead-letter queue. /*! \param srcQueueUrl: An Amazon SQS queue URL. \param deadLetterQueueARN: The Amazon Resource Name (ARN) of an Amazon SQS dead-letter queue. \param maxReceiveCount: The max receive count of a message before it is sent to the dead-letter queue. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::setDeadLetterQueue(const Aws::String &srcQueueUrl, const Aws::String &deadLetterQueueARN, int maxReceiveCount, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::String redrivePolicy = MakeRedrivePolicy(deadLetterQueueARN, maxReceiveCount); Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(srcQueueUrl); request.AddAttributes( Aws::SQS::Model::QueueAttributeName::RedrivePolicy, redrivePolicy); const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes(request); if (outcome.IsSuccess()) { std::cout << "Successfully set dead letter queue for queue " << srcQueueUrl << " to " << deadLetterQueueARN << std::endl; } else { std::cerr << "Error setting dead letter queue for queue " << srcQueueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } //! Make a redrive policy for a dead-letter queue. /*! \param queueArn: An Amazon SQS ARN for the dead-letter queue. \param maxReceiveCount: The max receive count of a message before it is sent to the dead-letter queue. \return Aws::String: Policy as JSON string. */ Aws::String MakeRedrivePolicy(const Aws::String &queueArn, int maxReceiveCount) { Aws::Utils::Json::JsonValue redrive_arn_entry; redrive_arn_entry.AsString(queueArn); Aws::Utils::Json::JsonValue max_msg_entry; max_msg_entry.AsInteger(maxReceiveCount); Aws::Utils::Json::JsonValue policy_map; policy_map.WithObject("deadLetterTargetArn", redrive_arn_entry); policy_map.WithObject("maxReceiveCount", max_msg_entry); return policy_map.View().WriteReadable(); }

設定 Amazon SQS 佇列以使用長輪詢。

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Set the wait time for an Amazon Simple Queue Service (Amazon SQS) queue poll. /*! \param queueUrl: An Amazon SQS queue URL. \param pollTimeSeconds: The receive message wait time in seconds. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::setQueueLongPollingAttribute(const Aws::String &queueURL, const Aws::String &pollTimeSeconds, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributes( Aws::SQS::Model::QueueAttributeName::ReceiveMessageWaitTimeSeconds, pollTimeSeconds); const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes( request); if (outcome.IsSuccess()) { std::cout << "Successfully updated long polling time for queue " << queueURL << " to " << pollTimeSeconds << std::endl; } else { std::cout << "Error updating long polling time for queue " << queueURL << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
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
SDK for Go V2
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) // 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(ctx context.Context, 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(ctx, &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
JavaScript
SDK for JavaScript (v3)
注意

還有更多 on 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; };

設定無效信件佇列。

import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; const DEAD_LETTER_QUEUE_ARN = "dead_letter_queue_arn"; export const main = async ( queueUrl = SQS_QUEUE_URL, deadLetterQueueArn = DEAD_LETTER_QUEUE_ARN, ) => { const command = new SetQueueAttributesCommand({ Attributes: { RedrivePolicy: JSON.stringify({ // Amazon SQS supports dead-letter queues (DLQ), which other // queues (source queues) can target for messages that can't // be processed (consumed) successfully. // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html deadLetterTargetArn: deadLetterQueueArn, maxReceiveCount: "10", }), }, QueueUrl: queueUrl, }); const response = await client.send(command); console.log(response); return response; };
  • 如需 API 詳細資訊,請參閱 SetQueueAttributes AWS SDK for JavaScript 參考中的 API

PowerShell
for PowerShell 工具

範例 1:此範例示範如何設定將佇列訂閱至 SNS 主題的政策。當訊息發佈至主題時,訊息會傳送至訂閱的佇列。

# create the queue and topic to be associated $qurl = New-SQSQueue -QueueName "myQueue" $topicarn = New-SNSTopic -Name "myTopic" # get the queue ARN to inject into the policy; it will be returned # in the output's QueueARN member but we need to put it into a variable # so text expansion in the policy string takes effect $qarn = (Get-SQSQueueAttribute -QueueUrl $qurl -AttributeName "QueueArn").QueueARN # construct the policy and inject arns $policy = @" { "Version": "2008-10-17", "Id": "$qarn/SQSPOLICY", "Statement": [ { "Sid": "1", "Effect": "Allow", "Principal": "*", "Action": "SQS:SendMessage", "Resource": "$qarn", "Condition": { "ArnEquals": { "aws:SourceArn": "$topicarn" } } } ] } "@ # set the policy Set-SQSQueueAttribute -QueueUrl $qurl -Attribute @{ Policy=$policy }

範例 2:此範例會設定指定佇列的指定屬性。

Set-SQSQueueAttribute -Attribute @{"DelaySeconds" = "10"; "MaximumMessageSize" = "131072"} -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 SetQueueAttributes