AWSDocAWS SDKGitHub サンプルリポジトリには、さらに多くの SDK サンプルがあります
翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
Amazon SQS メッセージを受信してタイムアウトの可視性を変更する
次のコード例は、Amazon SQS メッセージタイムアウトの可視性を変更する方法を示しています。
- C++
-
- SDK for C++
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Changes the visibility timeout of a message in an Amazon Simple Queue Service //! (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param messageReceiptHandle: A message receipt handle. \param visibilityTimeoutSeconds: Visibility timeout in seconds. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::changeMessageVisibility( const Aws::String &queue_url, const Aws::String &messageReceiptHandle, int visibilityTimeoutSeconds, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::ChangeMessageVisibilityRequest request; request.SetQueueUrl(queue_url); request.SetReceiptHandle(messageReceiptHandle); request.SetVisibilityTimeout(visibilityTimeoutSeconds); auto outcome = sqsClient.ChangeMessageVisibility(request); if (outcome.IsSuccess()) { std::cout << "Successfully changed visibility of message " << messageReceiptHandle << " from queue " << queue_url << std::endl; } else { std::cout << "Error changing visibility of message from queue " << queue_url << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
-
API の詳細については、AWS SDK for C++API ChangeMessageVisibilityリファレンスのを参照してください。
-
- Go
-
- SDK for Go V2
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 package main import ( "context" "flag" "fmt" "strconv" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" ) // SQSSetMsgVisibilityAPI defines the interface for the GetQueueUrl and ChangeMessageVisibility functions. // We use this interface to test the functions using a mocked service. type SQSSetMsgVisibilityAPI interface { GetQueueUrl(ctx context.Context, params *sqs.GetQueueUrlInput, optFns ...func(*sqs.Options)) (*sqs.GetQueueUrlOutput, error) ChangeMessageVisibility(ctx context.Context, params *sqs.ChangeMessageVisibilityInput, optFns ...func(*sqs.Options)) (*sqs.ChangeMessageVisibilityOutput, error) } // GetQueueURL gets the URL of an Amazon SQS queue. // Inputs: // c is the context of the method call, which includes the AWS Region. // api is the interface that defines the method call. // input defines the input arguments to the service call. // Output: // If success, a GetQueueUrlOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to GetQueueUrl. func GetQueueURL(c context.Context, api SQSSetMsgVisibilityAPI, input *sqs.GetQueueUrlInput) (*sqs.GetQueueUrlOutput, error) { return api.GetQueueUrl(c, input) } // SetMsgVisibility sets the visibility timeout for a message in an Amazon SQS queue. // Inputs: // c is the context of the method call, which includes the AWS Region. // api is the interface that defines the method call. // input defines the input arguments to the service call. // Output: // If success, a ChangeMessageVisibilityOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to ChangeMessageVisibility. func SetMsgVisibility(c context.Context, api SQSSetMsgVisibilityAPI, input *sqs.ChangeMessageVisibilityInput) (*sqs.ChangeMessageVisibilityOutput, error) { return api.ChangeMessageVisibility(c, input) } func main() { queue := flag.String("q", "", "The name of the queue") handle := flag.String("h", "", "The receipt handle of the message") visibility := flag.Int("v", 30, "The duration, in seconds, that the message is not visible to other consumers") flag.Parse() if *queue == "" || *handle == "" { fmt.Println("You must supply a queue name (-q QUEUE) and message receipt handle (-h HANDLE)") return } if *visibility < 0 { *visibility = 0 } if *visibility > 12*60*60 { *visibility = 12 * 60 * 60 } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := sqs.NewFromConfig(cfg) gQInput := &sqs.GetQueueUrlInput{ QueueName: queue, } // Get URL of queue urlResult, err := GetQueueURL(context.TODO(), client, gQInput) if err != nil { fmt.Println("Got an error getting the queue URL:") fmt.Println(err) return } queueURL := urlResult.QueueUrl sVInput := &sqs.ChangeMessageVisibilityInput{ ReceiptHandle: handle, QueueUrl: queueURL, VisibilityTimeout: int32(*visibility), } _, err = SetMsgVisibility(context.TODO(), client, sVInput) if err != nil { fmt.Println("Got an error setting the visibility of the message:") fmt.Println(err) return } fmt.Println("Changed the visibility of the message with the handle " + *handle + " in the " + *queue + " to " + strconv.Itoa(*visibility)) }
-
API の詳細については、AWS SDK for GoAPI ChangeMessageVisibility
リファレンスのを参照してください。
-
- JavaScript
-
- SDK forJavaScript v3)
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 クライアントを作成します。
import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };
Amazon SQS メッセージを受信し、タイムアウトの可視性を変更します。
// Import required AWS SDK clients and commands for Node.js import { ReceiveMessageCommand, ChangeMessageVisibilityCommand, } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const queueURL = "https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME"; // REGION, ACCOUNT_ID, QUEUE_NAME const params = { AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueURL, }; const run = async () => { try { const data = await sqsClient.send(new ReceiveMessageCommand(params)); if (data.Messages != null) { try { const visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, VisibilityTimeout: 20, // 20 second timeout }; const results = await sqsClient.send( new ChangeMessageVisibilityCommand(visibilityParams) ); console.log("Timeout Changed", results); } catch (err) { console.log("Delete Error", err); } } else { console.log("No messages to change"); } return data; // For unit tests. } catch (err) { console.log("Receive Error", err); } }; run();
-
詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。
-
API の詳細については、AWS SDK for JavaScriptAPI ChangeMessageVisibilityリファレンスのを参照してください。
-
- SDK forJavaScript v2)
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 Amazon SQS メッセージを受信し、タイムアウトの可視性を変更します。
// Load the AWS SDK for Node.js var AWS = require('aws-sdk') // Set the region to us-west-2 AWS.config.update({ region: 'us-west-2' }) // Create the SQS service object var sqs = new AWS.SQS({ apiVersion: '2012-11-05' }) var queueURL = 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' var params = { AttributeNames: ['SentTimestamp'], MaxNumberOfMessages: 1, MessageAttributeNames: ['All'], QueueUrl: queueURL } sqs.receiveMessage(params, function (err, data) { if (err) { console.log('Receive Error', err) } else { // Make sure we have a message if (data.Messages != null) { var visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, VisibilityTimeout: 20 // 20 second timeout } sqs.changeMessageVisibility(visibilityParams, function (err, data) { if (err) { console.log('Delete Error', err) } else { console.log('Timeout Changed', data) } }) } else { console.log('No messages to change') } } })
-
詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。
-
API の詳細については、AWS SDK for JavaScriptAPI ChangeMessageVisibilityリファレンスのを参照してください。
-
- Ruby
-
- SDK for Ruby
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 require "aws-sdk-sqs" # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. sqs = Aws::SQS::Client.new(region: "us-west-2") begin queue_name = "my-queue" queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url receive_message_result_before = sqs.receive_message({ queue_url: queue_url, max_number_of_messages: 10 # Receive up to 10 messages, if there are that many. }) puts "Before attempting to change message visibility timeout: received #{receive_message_result_before.messages.count} message(s)." receive_message_result_before.messages.each do |message| sqs.change_message_visibility({ queue_url: queue_url, receipt_handle: message.receipt_handle, visibility_timeout: 30 # This message will not be visible for 30 seconds after first receipt. }) end # Try to retrieve the original messages after setting their visibility timeout. receive_message_result_after = sqs.receive_message({ queue_url: queue_url, max_number_of_messages: 10 }) puts "\nAfter attempting to change message visibility timeout: received #{receive_message_result_after.messages.count} message(s)." rescue Aws::SQS::Errors::NonExistentQueue puts "Cannot receive messages for a queue named '#{receive_queue_name}', as it does not exist." end
-
API の詳細については、AWS SDK for RubyAPI ChangeMessageVisibilityリファレンスのを参照してください。
-