在开发过程中从 SQS 删除消息的最佳方法

发布于 2024-12-09 04:50:05 字数 90 浏览 1 评论 0原文

在开发过程中,我在 Amazon SQS 上生成了大量虚假消息。我正准备编写一个小应用程序来删除所有消息(这是我在开发过程中经常做的事情)。有人知道清除队列的工具吗?

During development, I'm generating a lot of bogus messages on my Amazon SQS. I was about to write a tiny app to delete all the messages (something I do frequently during development). Does anyone know of a tool to purge the queue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

阿楠 2024-12-16 04:50:05

如果您不想编写脚本或删除队列。您可以更改队列配置:

  1. 右键单击队列> 配置队列
  2. 消息保留期更改为1分钟(可以设置的最短时间)。
  3. 等待一段时间,让所有消息消失。

我发现这种方法非常适合删除队列中的所有消息而不删除队列。

If you don't want to write script or delete your queue. You can change the queue configuration:

  1. Right click on queue > configure queue
  2. Change Message Retention period to 1 minute (the minimum time it can be set to).
  3. Wait a while for all the messages to disappear.

I found that this way works well for deleting all messages in a queue without deleting the queue.

青朷 2024-12-16 04:50:05

截至 2014 年 12 月,sqs 控制台的队列操作菜单中现在有一个清除队列选项。

As of December 2014, the sqs console now has a purge queue option in the queue actions menu.

笑叹一世浮沉 2024-12-16 04:50:05

对于来到这里寻找一种在 C# 中批量删除 SQS 消息的方法的人...

//C# Console app which deletes all messages from a specified queue
//AWS .NET library required.

using System;
using System.Net;
using System.Configuration;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;

using Amazon;
using Amazon.SQS;
using Amazon.SQS.Model;
using System.Timers;

using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace QueueDeleter
{
    class Program
    {
        public static System.Timers.Timer myTimer;
        static NameValueCollection appConfig = ConfigurationManager.AppSettings;
        static string accessKeyID = appConfig["AWSAccessKey"];
        static string secretAccessKeyID = appConfig["AWSSecretKey"];
        static private AmazonSQS sqs;

        static string myQueueUrl = "https://queue.amazonaws.com/1640634564530223/myQueueUrl";
        public static String messageReceiptHandle;

        public static void Main(string[] args)
        {
            sqs = AWSClientFactory.CreateAmazonSQSClient(accessKeyID, secretAccessKeyID);

            myTimer = new System.Timers.Timer();
            myTimer.Interval = 10;
            myTimer.Elapsed += new ElapsedEventHandler(checkQueue);
            myTimer.AutoReset = true;
            myTimer.Start();
            Console.Read();
        }

        static void checkQueue(object source, ElapsedEventArgs e)
        {
            myTimer.Stop();

            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
            receiveMessageRequest.QueueUrl = myQueueUrl;
            ReceiveMessageResponse receiveMessageResponse = sqs.ReceiveMessage(receiveMessageRequest);
            if (receiveMessageResponse.IsSetReceiveMessageResult())
            {
                ReceiveMessageResult receiveMessageResult = receiveMessageResponse.ReceiveMessageResult;

                if (receiveMessageResult.Message.Count < 1)
                {
                    Console.WriteLine("Can't find any visible messages.");
                    myTimer.Start();
                    return;
                }

            foreach (Message message in receiveMessageResult.Message)
            {
                Console.WriteLine("Printing received message.\n");

                messageReceiptHandle = message.ReceiptHandle;

                Console.WriteLine("Message Body:");
                if (message.IsSetBody())
                {
                    Console.WriteLine("    Body: {0}", message.Body);
                }
                sqs.DeleteMessage(new DeleteMessageRequest().WithQueueUrl(myQueueUrl).WithReceiptHandle(messageReceiptHandle));
            }
        }
        else
        {
            Console.WriteLine("No new messages.");
        }

         myTimer.Start();
        }
    }
}

For anyone who has come here, looking for a way to delete SQS messages en masse in C#...

//C# Console app which deletes all messages from a specified queue
//AWS .NET library required.

using System;
using System.Net;
using System.Configuration;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;

using Amazon;
using Amazon.SQS;
using Amazon.SQS.Model;
using System.Timers;

using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace QueueDeleter
{
    class Program
    {
        public static System.Timers.Timer myTimer;
        static NameValueCollection appConfig = ConfigurationManager.AppSettings;
        static string accessKeyID = appConfig["AWSAccessKey"];
        static string secretAccessKeyID = appConfig["AWSSecretKey"];
        static private AmazonSQS sqs;

        static string myQueueUrl = "https://queue.amazonaws.com/1640634564530223/myQueueUrl";
        public static String messageReceiptHandle;

        public static void Main(string[] args)
        {
            sqs = AWSClientFactory.CreateAmazonSQSClient(accessKeyID, secretAccessKeyID);

            myTimer = new System.Timers.Timer();
            myTimer.Interval = 10;
            myTimer.Elapsed += new ElapsedEventHandler(checkQueue);
            myTimer.AutoReset = true;
            myTimer.Start();
            Console.Read();
        }

        static void checkQueue(object source, ElapsedEventArgs e)
        {
            myTimer.Stop();

            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
            receiveMessageRequest.QueueUrl = myQueueUrl;
            ReceiveMessageResponse receiveMessageResponse = sqs.ReceiveMessage(receiveMessageRequest);
            if (receiveMessageResponse.IsSetReceiveMessageResult())
            {
                ReceiveMessageResult receiveMessageResult = receiveMessageResponse.ReceiveMessageResult;

                if (receiveMessageResult.Message.Count < 1)
                {
                    Console.WriteLine("Can't find any visible messages.");
                    myTimer.Start();
                    return;
                }

            foreach (Message message in receiveMessageResult.Message)
            {
                Console.WriteLine("Printing received message.\n");

                messageReceiptHandle = message.ReceiptHandle;

                Console.WriteLine("Message Body:");
                if (message.IsSetBody())
                {
                    Console.WriteLine("    Body: {0}", message.Body);
                }
                sqs.DeleteMessage(new DeleteMessageRequest().WithQueueUrl(myQueueUrl).WithReceiptHandle(messageReceiptHandle));
            }
        }
        else
        {
            Console.WriteLine("No new messages.");
        }

         myTimer.Start();
        }
    }
}
◇流星雨 2024-12-16 04:50:05

检查队列中的第一项。向下滚动到队列中的最后一项。
按住 Shift 键,单击项目。全部都会被选中。

Check the first item in queue. Scroll down to last item in queue.
Hold shift, click on item. All will be selected.

可爱暴击 2024-12-16 04:50:05

我认为最好的方法是删除队列并重新创建它,只需 2 个请求。

I think the best way would be to delete the queue and create it again, just 2 requests.

悲念泪 2024-12-16 04:50:05

我认为最好的方法是将保留期更改为 1 分钟,但如果有人需要,这里是 Python 代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import boto.sqs
from boto.sqs.message import Message
import time
import os

startTime = program_start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

### Lets connect to SQS:
qcon = boto.sqs.connect_to_region(region,aws_access_key_id='xxx',aws_secret_access_key='xxx')
SHQueue = qcon.get_queue('SQS')
m = Message()
### Read file and write to SQS
counter = 0
while counter < 1000:   ## For deleting 1000*10 items, change to True if you want delete all
    links = SHQueue.get_messages(10)
    for link in links:
            m = link
            SHQueue.delete_message(m)
    counter += 1
#### The End
print "\n\nTerminating...\n"
print "Start: ", program_start_time
print "End time: ", time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

I think best way is changing Retention period to 1 minute, but here is Python code if someone needs:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import boto.sqs
from boto.sqs.message import Message
import time
import os

startTime = program_start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

### Lets connect to SQS:
qcon = boto.sqs.connect_to_region(region,aws_access_key_id='xxx',aws_secret_access_key='xxx')
SHQueue = qcon.get_queue('SQS')
m = Message()
### Read file and write to SQS
counter = 0
while counter < 1000:   ## For deleting 1000*10 items, change to True if you want delete all
    links = SHQueue.get_messages(10)
    for link in links:
            m = link
            SHQueue.delete_message(m)
    counter += 1
#### The End
print "\n\nTerminating...\n"
print "Start: ", program_start_time
print "End time: ", time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
梦归所梦 2024-12-16 04:50:05

选项 1:boto sqs 有一个适用于 python 的 purge_queue 方法:

purge_queue(queue)
Purge all messages in an SQS Queue.

Parameters: queue (A Queue object) – The SQS queue to be purged
Return type:    bool
Returns:    True if the command succeeded, False otherwise

来源:http://boto.readthedocs.org/en/latest/ref/sqs.html

对我有用的代码:

conn = boto.sqs.connect_to_region('us-east-1',
          aws_access_key_id=AWS_ACCESS_KEY_ID,
          aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
)
q = conn.create_queue("blah")
#add some messages here

#invoke the purge_queue method of the conn, and pass in the
#queue to purge.
conn.purge_queue(self.queue)

对我来说,它删除了队列。但是,Amazon SQS 仅允许您每 60 秒运行一次。所以我不得不使用下面的辅助解决方案:

选项 2:通过在 while 循环中消耗所有消息并将它们扔掉来进行清除:

    all_messages = []
    rs = self.queue.get_messages(10)
    while len(rs) > 0:
        all_messages.extend(rs)
        rs = self.queue.get_messages(10)

Option 1: boto sqs has a purge_queue method for python:

purge_queue(queue)
Purge all messages in an SQS Queue.

Parameters: queue (A Queue object) – The SQS queue to be purged
Return type:    bool
Returns:    True if the command succeeded, False otherwise

Source: http://boto.readthedocs.org/en/latest/ref/sqs.html

Code that works for me:

conn = boto.sqs.connect_to_region('us-east-1',
          aws_access_key_id=AWS_ACCESS_KEY_ID,
          aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
)
q = conn.create_queue("blah")
#add some messages here

#invoke the purge_queue method of the conn, and pass in the
#queue to purge.
conn.purge_queue(self.queue)

For me, it deleted the queue. However, Amazon SQS only lets you run this once every 60 seconds. So I had to use the secondary solution below:

Option 2: Do a purge by consuming all messages in a while loop and throwing them out:

    all_messages = []
    rs = self.queue.get_messages(10)
    while len(rs) > 0:
        all_messages.extend(rs)
        rs = self.queue.get_messages(10)
心碎的声音 2024-12-16 04:50:05

如果您有权访问 AWS 控制台,则可以使用 Web UI 清除队列。

步骤:

  • 导航至服务 -> SQS
  • 按您的“QUEUE_NAME”过滤队列
  • 右键单击​​您的队列名称 ->清除队列

这将请求清除队列,这应该在 5 或 10 秒左右完成。

请参阅下文了解如何执行此操作:

手动清除队列

If you have access to the AWS console, you can purge a queue using the Web UI.

Steps:

  • Navigate to Services -> SQS
  • Filter queues by your "QUEUE_NAME"
  • Right-click on your queue name -> Purge queue

This will request for the queue to be cleared and this should be completed with 5 or 10 seconds or so.

See below for how to perform this operation:

Purge queue manually

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文