[英]python-requests with multithreading
我正在創建一個HTTP客戶端,它可以每秒生成數百個連接,並在每個連接上發送最多10個請求。 我正在使用線程,因此可以實現並發。 這是我的代碼:
def generate_req(reqSession):
requestCounter = 0
while requestCounter < requestRate:
try:
response1 = reqSession.get('http://20.20.1.2/tempurl.html')
if response1.status_code == 200:
client_notify('r')
except(exceptions.ConnectionError, exceptions.HTTPError, exceptions.Timeout) as Err:
client_notify('F')
break
requestCounter += 1
def main():
for q in range(connectionPerSec):
s1 = requests.session()
t1 = threading.Thread(target=generate_req, args=(s1,))
t1.start()
問題:
在requestRate = 1的情況下,它不會超過200個連接/秒。我在同一個客戶端計算機上運行其他可用的HTTP客戶端,並且在服務器上運行,測試運行正常並且能夠擴展。
當requestRate = 10時,connections / sec降至30.原因:無法每秒創建目標數量的線程。
對於問題#2,客戶端計算機無法創建足夠的請求會話並啟動新線程。 一旦requestRate設置為大於1,事情就會開始崩潰。 我懷疑它與請求使用的HTTP連接池有關。
請在這里建議我做錯了什么。
我無法解決問題,但以下代碼有一些新功能:
1)擴展日志記錄,包括特定的每線程信息
2)所有線程在末尾join()
,以確保父進程不會掛起它們
3)多線程print
傾向於交錯消息,這可能是笨拙的。 此版本使用yield
因此將來的版本可以接受消息並清楚地打印它們。
import exceptions, requests, threading, time
requestRate = 1
connectionPerSec = 2
def client_notify(msg):
return time.time(), threading.current_thread().name, msg
def generate_req(reqSession):
requestCounter = 0
while requestCounter < requestRate:
try:
response1 = reqSession.get('http://127.0.0.1/')
if response1.status_code == 200:
print client_notify('r')
except (exceptions.ConnectionError, exceptions.HTTPError, exceptions.Timeout):
print client_notify('F')
break
requestCounter += 1
def main():
for cnum in range(connectionPerSec):
s1 = requests.session()
th = threading.Thread(
target=generate_req, args=(s1,),
name='thread-{:03d}'.format(cnum),
)
th.start()
for th in threading.enumerate():
if th != threading.current_thread():
th.join()
if __name__=='__main__':
main()
(1407275951.954147, 'thread-000', 'r')
(1407275951.95479, 'thread-001', 'r')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.