挂起线程使用连接池的异步请求

时间:2015-11-13 10:21:02

标签: python multithreading python-requests connection-pooling

对于项目,我们需要通过API(HTTP / 1.1)请求数据,根据您发现的内容,您可以发送带有指令的request.post,之后API将发回响应。我使程序多线程,以便主程序不断请求数据,以防我想发布一个指令,我产生一个线程来做到这一点。 (请求数据只需1秒,其中发布指令和获取回复最多可能需要3秒才能响应)

然而我遇到的问题是,有时我的一个线程会挂起并且只有在我发出命令thread.join()时才会完成。我可以看到它挂起,因为我在主线程中获得的数据应该类似于我的先前的指令(由线程发送),(我允许服务器的5秒周期类似于我之前发送的指令,因此不是服务器尚未更新的情况)。如果我现在再次发送相同的指令,我会发现现在两个指令都发送到服务器(挂起的指令和新发布的指令)。因此,以某种方式发送新指令会产生副作用,之前的指令也会发送。

问题看起来与线程有关,因为我的代码在执行串行时不会挂起。查看像this这样的帖子没有帮助,因为我事先并不知道我的异步请求需要什么。重要的是我要使用持久连接并重用它们,因为这样可以节省大量的握手时间等。

我的问题:

  • 以多线程方式处理持久连接的连接池的正确方法是什么。 (所以它不会挂起)
  • 如何调试/排除线程故障以找出它挂起的位置。
  • 请求经常被推荐为一个包,但也许还有其他的,更适合这种应用程序?

示例代码:

import requests
from threading import Thread

req = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections = 10, pool_maxsize=10)
req.mount('',adapter)

url='http://python-requests.org'

def main(url=''):
    thread_list=[]
    counter=0
    while True:
        resp = req.get(url)
        interesting = 1 #
        if interesting:
            instructions = {}
            a = Thread(target = send_instructions, kwargs = dict(url = url, instructions = instructions))
            a.start()
            thread_list.append(a)
        tmp=[]
        for x in thread_list:
            if x.isAlive():
                tmp.append(x)
        thread_list = tmp
        if counter>10:
            break
        counter+=1

def send_instructions(url='', instructions=''):
    resp=req.post(url, headers = instructions)
    print(resp)

main(url)

0 个答案:

没有答案
相关问题