前因:
請求接口次數很多,每日兩億多次,主要是有些接口返回數據量很大高達110KB(為了減少請求次數,將多個接口合並成一個導致的)。
后端接口的nginx已經開啟gzip,所以做個測試,看看是否在請求時使用壓縮解壓
php CURL 的擴展安裝這里就不說了
用到的curl的兩個參數
//在http 請求頭加入 gzip壓縮
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding:gzip'));
//curl返回的結果,采用gzip解壓
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
1、不使用壓縮解壓
$s1 = microtime(true);
$ch = curl_init();
for($i=0; $i<100;$i++){
$url="http://192.168.0.11:8080/xxxxx/xxxxx?";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$data = curl_exec($ch);
}
curl_close($ch);
echo microtime(true)-$s1;
echo "\n";
測試結果 請求100次平均耗時 2.1s 0.021s/次
2、使用壓縮解壓
$s1 = microtime(true);
$ch = curl_init();
for($i=0; $i<100;$i++){
$url="http://192.168.0.1:8080/xxxxx/xxxxx?";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding:gzip'));
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
$data = curl_exec($ch);
}
curl_close($ch);
echo microtime(true)-$s1;
echo "\n";
測試結果 請求100次平均耗時 2.6s 0.026/次
結果
1、不使用壓縮比使用壓縮 請求一次快 5ms 2、千兆網,在局域網內傳輸這些數據大概是 0.7ms
結論
暫時不使用 curl 的壓縮和解壓
