获取 Amazon SQS 队列中的消息数量

33

一个简单的问题,但我找不到答案。

是否可以使用API获取AWS SQS队列的队列大小(等待处理的消息/作业数量)?

最好使用cURL或PHP SDK。


Java开发者请查看:https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueAttributes.html - ImtiazeA
7个回答

18

我相信您要查找的是 get-queue-attributes,也许会查询ApproximateNumberOfMessages属性。


1
还可以在AWS SDK for PHP中使用:http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.Sqs.SqsClient.html#_getQueueAttributes - Jeremy Lindblom
"ApproximateNumberOfMessages"是一个不错的方式。但是如果有多个消费者从队列中消费,这可能会不准确。 - Keet Sugathadasa
这个值是相对快速更新还是实时更新的?入队/出队后更新此值的延迟有什么想法吗? - Kubie

18

并附带一些代码示例:

aws sqs get-queue-attributes --queue-url https://sqs.<region>.amazonaws.com/<accountId>/<SQS name> --attribute-names All


{
    "Attributes": {
        "QueueArn": "arn:aws:sqs:<region>:<accountId>:<SQS name>",
        "ApproximateNumberOfMessages": "0",
        "ApproximateNumberOfMessagesNotVisible": "3",
        "ApproximateNumberOfMessagesDelayed": "0",
        "CreatedTimestamp": "1594729555",
        "LastModifiedTimestamp": "1595845586",
        "VisibilityTimeout": "60",
        "MaximumMessageSize": "262144",
        "MessageRetentionPeriod": "900",
        "DelaySeconds": "0",
        "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:<region>:<accountId>:<DLQ name>\",\"maxReceiveCount\":3}",
        "ReceiveMessageWaitTimeSeconds": "0"
    }
}

获取已定义属性的值:

 aws sqs get-queue-attributes --queue-url https://sqs.<region>.amazonaws.com/<accountId>/<SQS name> --attribute-names VisibilityTimeout ApproximateNumberOfMessages ApproximateNumberOfMessagesNotVisible ApproximateNumberOfMessagesDelayed

{
    "Attributes": {
        "VisibilityTimeout": "60",
        "ApproximateNumberOfMessages": "0",
        "ApproximateNumberOfMessagesNotVisible": "3",
        "ApproximateNumberOfMessagesDelayed": "0"
    }
}

警告

在生产者停止发送消息后至少1分钟,ApproximateNumberOfMessagesDelayedApproximateNumberOfMessagesNotVisibleApproximateNumberOfMessagesVisible指标可能无法达到一致性。这段时间用于队列元数据达到最终一致性。


13
你可以获取队列属性并查找相关属性(请参见此链接)。您可能需要查看以下两个属性。

ApproximateNumberOfMessages - 返回队列中可见消息的大致数量

ApproximateNumberOfMessagesNotVisible - 返回未超时且未删除的消息的大约数量。

如果您想包括等待添加的消息,请考虑以下属性。

ApproximateNumberOfMessagesDelayed - 返回正在等待添加到队列中的消息的大约数量。

最后,对上述属性返回的值进行总计,并获得当前队列的大小。


这些值是相对快速更新还是实时更新的?您有关于入队/出队后值更新的延迟时间的任何想法吗? - Kubie

1
对于PHP,请尝试这个,
        $sqsClient = new  SqsClient([
            'region' => env('AWS_REGION'),
            'version' => '2012-11-05',
            'credentials' => [
                'key'    => env('AWS_ACCESS_KEY'),
                'secret' => env('AWS_SECRET_KEY'),
            ],
        ]);

        $sqs = new SqsQueue($sqsClient,null,null);
        $size = $sqs->size(env('AWS_SQS_URL'));

        echo $size;

0
以下代码使用AWS PHP SDK V3首先获取队列URL,然后获取所请求队列的ApproximateNumberOfMessagesApproximateNumberOfMessagesDelayedApproximateNumberOfMessagesNotVisible属性: ApproximateNumberOfMessages - 返回可从队列检索的消息的大致数量。 ApproximateNumberOfMessagesDelayed - 返回队列中延迟且无法立即读取的消息的大约数量。当队列配置为延迟队列或使用延迟参数发送消息时,可能会发生这种情况。 ApproximateNumberOfMessagesNotVisible - 返回正在传输中的消息的大约数量。如果已将消息发送到客户端但尚未删除或尚未到达其可见性窗口,则认为消息正在传输中。
require 'vendor/autoload.php';

use Aws\Sqs\SqsClient; 
use Aws\Exception\AwsException;


$queueName = "SQS_QUEUE_NAME";
 
$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->getQueueUrl([
        'QueueName' => $queueName
    ]);
    
    $queueUrl = $result['QueueUrl'];
    $result = $client->getQueueAttributes([
        'AttributeNames' => ['ApproximateNumberOfMessages', 'ApproximateNumberOfMessagesDelayed', 'ApproximateNumberOfMessagesNotVisible'],
        'QueueUrl' => $queueUrl,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}

0

你可以使用JQ仅获取值的输出:

$AWSProdAccountID = "1234567890"

$ProductionErrorMsgCount = aws sqs get-queue-attributes --queue-url https://sqs.<region>.amazonaws.com/$AWSProdAccountID/<SQS name> --attribute-names ApproximateNumberOfMessages --profile $AWSProfile --region ap-southeast-2 | jq.exe -r ".Attributes.ApproximateNumberOfMessages[:1]"

0

使用 PHP:

putenv('AWS_ACCESS_TOKEN=xxxx');
putenv('AWS_ACCESS_TOKEN_SECRET=xxxx'); 

$sqs = new \Aws\Sqs\SqsClient([
    'profile' => 'default',
    'region' => 'REGION',
    'version' => 'latest'
]);

$queueUrl = 'https://sqs.REGION.amazonaws.com/xxxxxxxx/queue-name';

$x = $sqs->getQueueAttributes([
    'QueueUrl' => $queueUrl, 
    'AttributeNames' => ['All']
]);

echo json_encode($x->toArray(), JSON_PRETTY_PRINT);

将会输出类似于以下内容:

{
    "Attributes": {
        "QueueArn": "arn:aws:sqs:REGION:xxxxxxx:queue-name",
        "ApproximateNumberOfMessages": "0",
        "ApproximateNumberOfMessagesNotVisible": "0",
        "ApproximateNumberOfMessagesDelayed": "0",
        "CreatedTimestamp": "1587472818",
        "LastModifiedTimestamp": "1587473783",
        "VisibilityTimeout": "30",
        "MaximumMessageSize": "262144",
        "MessageRetentionPeriod": "345600",
        "DelaySeconds": "0",
        "ReceiveMessageWaitTimeSeconds": "0",
        "KmsMasterKeyId": "alias\/aws\/sqs",
        "KmsDataKeyReusePeriodSeconds": "300",
        "FifoQueue": "true",
        "ContentBasedDeduplication": "false"
    },
    "@metadata": {
       ....
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接