如何确定 SQS 队列正在工作或为空

How to Identify that an SQS Queue is working or empty

我有一个 SQS 队列,在向该队列发送消息之前,我需要确定其中有活动消息。我正在使用以下打字稿代码来捕捉这一点。

const queueUrl = 'https://sqs.' + 'MY_QUEUE';
const sqsClient = new SQSClient({region: process.env.AWS_DEFAULT_REGION});

const getQueueAttributesCommandInput: GetQueueAttributesCommandInput = {
  QueueUrl: queueUrl,
  AttributeNames: ['All']
};

const getQueueAttributesCommandOutput = await sqsClient.send(new GetQueueAttributesCommand(getQueueAttributesCommandInput));
if (getQueueAttributesCommandOutput.$metadata.httpStatusCode !== 200) {
  return new ErrorCustom(this.sqsFetchError, 400, {});
}

const approximateNumberOfMessages = +getQueueAttributesCommandOutput.Attributes['ApproximateNumberOfMessages'];
const approximateNumberOfMessagesNotVisible = +getQueueAttributesCommandOutput.Attributes['ApproximateNumberOfMessagesNotVisible'];
const approximateNumberOfMessagesDelayed = +getQueueAttributesCommandOutput.Attributes['ApproximateNumberOfMessagesDelayed'];
if (approximateNumberOfMessages + approximateNumberOfMessagesNotVisible + approximateNumberOfMessagesDelayed !== 0) {
  return new ErrorCustom(this.sqsIsActivePleaseTryAgain, 400, {});
}

这是正确的做法吗?如果不是,我如何确定 SQS 队列是活动的还是空的?

在此文档中 https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/confirm-queue-is-empty.html 它说:

When all of them are 0 for several minutes, the queue is empty.

我只想问一下,这些属性统计的实时性如何,10秒的空结果就够了

干杯。

看来您的要求是:

  • 确保每条消息都按严格顺序处理
  • 不要向Lambda函数发送多条消息(怕超时)

我会推荐:

  • 使用 Amazon SQS FIFO (First-In, First-Out) 队列
  • 批量大小设置为 1 以仅向 Lambda 函数发送一条消息
  • 对每条消息使用 same MessageGroupId -- 这将确保 Lambda 不会在处理一条消息时处理另一条具有相同 ID 的消息