且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Python中的boto库获取Amazon SQS中的消息接收计数?

更新时间:2023-11-25 13:32:58

至少有两种方法可以做到这一点.

There are at least a couple of ways of doing this.

当您在boto中读取消息时,您会收到一个Message对象或其某些子类.消息对象具有一个属性"字段,该字段是一个包含SQS已知的所有消息属性的字典.SQS跟踪的事情之一是大约已读取消息的次数.因此,您可以使用此值来确定是否应删除邮件,但是您必须对值的近似"性质感到满意.

When you read a message in boto, you receive a Message object or some subclass thereof. The Message object has an "attributes" field that is a dict containing all message attributes known by SQS. One of the things SQS tracks is the approximate # of times the message has been read. So, you could use this value to determine whether the message should be deleted or not but you would have to be comfortable with the "approximate" nature of the value.

或者,您可以在某种数据库中记录消息ID,并在每次阅读消息时在数据库中增加一个count字段.如果始终在单个进程中读取消息,则可以通过简单的Python字典来完成;如果需要记录跨进程的读数,则可以使用SimpleDB之类的方法来完成.

Alternatively, you could record message ID's in some sort of database and increment a count field in the database each time you read the message. This could be done in a simple Python dict if the messages are always being read within a single process or it could be done in something like SimpleDB if you need to record readings across processes.

希望有帮助.

下面是一些示例代码:

>>> import boto.sqs
>>> c = boto.sqs.connect_to_region()
>>> q = c.lookup('myqueue')
>>> messages = c.receive_message(q, num_messages=1, attributes='All')
>>> messages[0].attributes
{u'ApproximateFirstReceiveTimestamp': u'1365474374620',
 u'ApproximateReceiveCount': u'2',
 u'SenderId': u'419278470775',
 u'SentTimestamp': u'1365474360357'}
>>>