1. 程式人生 > >模擬高併發請求服務端(python gevent)

模擬高併發請求服務端(python gevent)

專案背景:對web後端進行高併發的請求,簡單測試服務框架的效能
解決思路:利用python的多執行緒,但python的多執行緒有點“雞肋”, 個人選擇使用簡潔輕便gevent。
解決方案:採用gevent非同步 + requests 進行高併發請求

import time
import json
import random
from urllib.error import URLError
from urllib import request
import http.client
import requests
import gevent
from gevent import monkey
# 補丁
monkey.patch_all()


**請求URL**
url = 'http://127.0.0.1:8000/insert'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1;WOW64; rv:45.0) Gecko/20100101 Firefox/45.0'
}


def make_data(num):
    """製造請求資料"""
    data = { 
            "id": num,   
            "name": "test" + num,
    }
    return data


def run():
    """三種模擬請求"""
    num = random.randint(100, 999)
    data = make_data(num)
    try:
        # s1:request請求
        req = request.Request(url=url, data=data, headers=headers, method="POST")
        response = request.urlopen(req)
        resp = response.read()
        print("伺服器返回值為:\n", resp.decode('utf-8'))
        
        # s2:httpclient請求
        # httpclient = http.client.HTTPConnection(host='127.0.0.1', port=8001)
        # httpclient.request("POST", '/insert', data, headers)
        # response = httpclient.getresponse()
        # print(response.read().decode())

        # s3:requests請求
        # resp = requests.post(url=url, data=data, headers=headers)
        # print("狀態:\n", resp)
        # print("請求頭:\n", resp.headers)
        # print("伺服器返回值為:\n", resp.content.decode())
    except URLError as e:
        print('請求', e)
    except Exception as e:
        print('請求錯誤:', e)


def call_gevent(count):
    """呼叫gevent 模擬高併發"""
    begin_time = time.time()
    run_gevent_list = []
    for i in range(count):
        print('--------------%d--Test-------------' % i)
        run_gevent_list.append(gevent.spawn(run()))
    gevent.joinall(run_gevent_list)
    end = time.time()
    print('單次測試時間(平均)s:', (end - begin_time) / count)
    print('累計測試時間 s:', end - begin_time)


if __name__ == '__main__':
    # 10萬併發請求
    test_count = 100000
    call_gevent(count=test_count)