nginx優化之request_time 和upstream_response_time差別


在nginx配置中,經常看到request_time,upstream_response_time,有些時間並不是很清楚二者的差異,感覺差不多,其實:

本質是requst_time是從client發起請求到返回結果的時間;而upstream_response_time是nginx建立連接到返回結果的時間,固然中間的時間是網絡開銷的時間,所以一般來說requset_time大,而接口的相應時間慢的話,一般看后者。

1、request_time

官網描述:request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client 。
指的就是從接受用戶請求的第一個字節到發送完響應數據的時間,即包括接收請求數據時間、程序響應時間、輸出響應數據時間。
 
2、upstream_response_time
官網描述:keeps times of responses obtained from upstream servers; times are kept in seconds with a milliseconds resolution. Several response times are separated by commas and colons like addresses in the $upstream_addr variable
 
是指從Nginx向后端(php-cgi)建立連接開始到接受完數據然后關閉連接為止的時間。
 
從上面的描述可以看出,$request_time肯定大於等於$upstream_response_time,特別是使用POST方式傳遞參數時,因為Nginx會把request body緩存住,接受完畢后才會把數據一起發給后端。所以如果用戶網絡較差,或者傳遞數據較大時,$request_time會比$upstream_response_time大很多。
 
所以如果使用nginx的accesslog查看php程序中哪些接口比較慢的話,記得在log_format中加入$upstream_response_time。
 
根據引貼對官網描述的翻譯:
upstream_response_time:從 Nginx 建立連接 到 接收完數據並關閉連接
request_time:從 接受用戶請求的第一個字節 到 發送完響應數據

如果把整個過程補充起來的話 應該是:
[1用戶請求][2建立 Nginx 連接][3發送響應][4接收響應][5關閉  Nginx 連接]
那么 upstream_response_time 就是 2+3+4+5 
但是 一般這里面可以認為 [5關閉 Nginx 連接] 的耗時接近 0
所以 upstream_response_time 實際上就是 2+3+4 
而 request_time 是 1+2+3+4
二者之間相差的就是 [1用戶請求] 的時間

如果用戶端網絡狀況較差 或者傳遞數據本身較大 
再考慮到 當使用 POST 方式傳參時 Nginx 會先把 request body 緩存起來
而這些耗時都會累積到 [1用戶請求] 頭上去
這樣就解釋了
為什么 request_time 有可能會比 upstream_response_time 要大

因為用戶端的狀況通常千差萬別 無法控制 
所以並不應該被納入到測試和調優的范疇里面
更值得關注的應該是 upstream_response_time
所以在實際工作中 如果想要關心哪些請求比較慢的話 
記得要在配置文件的 log_format 中加入 $upstream_response_time  
 
參考: https://www.cnblogs.com/dongruiha/p/7007801.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM