我使用的架構是python的fastAPI,一個簡單的hello world,加一個sleep(2)模拟耗時操作。代碼如下:
import time
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
time.sleep(2) # 模拟耗時操作
return {"Hello": "World"}
先單程序啟動
啟動指令:
uvicorn --host 0.0.0.0 --port 5000 --workers 1 yourfilename:app
使用的測試工具是ab(Apache Benchmark)。測試的時候為了避免幹擾,最好将ab和服務放在不同的機器上。
-c 和 -n 參數可以從小到大慢慢增加:
當并發數為 50 請求數為1000 時:
> ab -c 50 -n 1000 your_url
Requests per second: 5.87 [#/sec] (mean)
Time per request: 8518.141 [ms] (mean)
當并發數為 100 請求數為1000 時:
> ab -c 100 -n 1000 your_url
Requests per second: 5.87 [#/sec] (mean)
Time per request: 17034.188 [ms] (mean)
可以看到,平均每秒處理的請求數不變,單個請求的響應時間變長了
使用多程序啟動:
uvicorn --host 0.0.0.0 --port 5000 --workers 4 yourfilename:app
當并發數為 100 請求數為1000 時:
> ab -c 100 -n 1000 your_url
Requests per second: 21.66 [#/sec] (mean)
Time per request: 4617.610 [ms] (mean)
可以看到,使用多程序,平均每秒處理的請求數變多了,單個請求的響應時間也變短了
nginx負載均衡
當并發量超過一定數量,一台機器也難以承受,這時候可以部署多台伺服器,然後用nginx做負載均衡。
nginx的關鍵配置:
http {
……
upstream load_balance_test {
server 1.1.1.1:5000; # 你的多台伺服器
server 192.168.1.1:5000;
}
server {
listen 80;
……
location / {
proxy_pass http://load_balance_test;
}
}
……
}
這次同樣是 并發數 100 請求數1000,請求位址是nginx所監聽的位址:
> ab -c 100 -n 1000 nginx位址:端口
Requests per second: 33.19 [#/sec] (mean)
Time per request: 3012.560 [ms] (mean)