线程轮询 sqs 并将其添加到 python 队列中以处理模具

Cod*_*oid 6 python queue multithreading amazon-sqs

我有一段多线程代码 - 3 个线程,用于从 SQS 轮询数据并将其添加到 python 队列中。5 个线程从 python 队列中获取消息,处理它们并将其发送到后端系统。

这是代码:

python_queue = Queue.Queue()

class GetDataFromSQS(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, python_queue):
        threading.Thread.__init__(self)
        self.python_queue = python_queue

    def run(self):
        while True:
            time.sleep(0.5) //sleep for a few secs before querying again
            try:
                msgs = sqs_queue.get_messages(10)
                if msgs == None:
                    print "sqs is empty now"!
                for msg in msgs:
                    #place each message block from sqs into python queue for processing
                    self.python_queue.put(msg)
                    print "Adding a new message to Queue. Queue size is now %d" % self.python_queue.qsize()
                    #delete from sqs
                    sqs_queue.delete_message(msg)
            except Exception as e:
                print "Exception in GetDataFromSQS :: " +  e


class ProcessSQSMsgs(threading.Thread):
    def __init__(self, python_queue):
        threading.Thread.__init__(self)
        self.python_queue = python_queue
        self.pool_manager = PoolManager(num_pools=6)

    def run(self):
        while True:
            #grabs the message to be parsed from sqs queue
            python_queue_msg = self.python_queue.get()
            try:
                processMsgAndSendToBackend(python_queue_msg, self.pool_manager)
            except Exception as e:
                print "Error parsing:: " + e
            finally:
                self.python_queue.task_done()

def processMsgAndSendToBackend(msg, pool_manager):
    if msg != "":
        ###### All the code related to processing the msg
        for individualValue in processedMsg:
            try:
                response = pool_manager.urlopen('POST', backend_endpoint, body=individualValue)
                if response == None:
                    print "Error"
                else:
                    response.release_conn()
            except Exception as e:
                print "Exception! Post data to backend: " + e


def startMyPython():
    #spawn a pool of threads, and pass them queue instance
    for i in range(3):
        sqsThread = GetDataFromSQS(python_queue)
        sqsThread.start()

    for j in range(5):
        parseThread = ProcessSQSMsgs(python_queue)
        #parseThread.setDaemon(True)
        parseThread.start()

    #wait on the queue until everything has been processed
    python_queue.join()
    # python_queue.close() -- should i do this?

startMyPython()
Run Code Online (Sandbox Code Playgroud)

问题: 3 个 python 工作人员每隔几天随机死亡一次(使用 top -p -H 进行监控),如果我终止进程并再次启动脚本,一切都会好起来。我怀疑消失的工作线程是 3 个 GetDataFromSQS 线程。因为 GetDataFromSQS 死掉了,其他 5 个工作线程虽然正在运行,但总是处于睡眠状态,因为 python 队列中没有数据。我不确定我在这里做错了什么,因为我对 python 还很陌生,并且按照本教程创建了这个排队逻辑和线程 - http://www.ibm.com/developerworks/aix/library/au-threadingpython/

在此先感谢您的帮助。希望我已经清楚地解释了我的问题。

Cod*_*oid 6

线程挂起的问题与获取 sqs 队列的句柄有关。我使用 IAM 来管理凭证,使用 boto sdk 来连接到 sqs。

此问题的根本原因是 boto 包正在从 AWS 读取身份验证元数据,并且偶尔会失败。

修复方法是编辑 boto 配置,增加对 AWS 执行身份验证调用的尝试次数。

[Boto]metadata_service_num_attempts = 5

https://groups.google.com/forum/#!topic/boto-users/1yX24WG3g1E