問題
Nodejs原生的http.request 方法是不支援設定逾時參數的,
而網路請求經常會遇到逾時的情況,特別是對於外部網路,如果不處理逾時,發起的請求將會一直卡主,消耗的系統資源也不能及時被釋放。
解決方案(舊)
定時器:通過定時器,當timeout事件觸發的時候,主動調用req.abort() 終止請求,
然後返回逾時異常。
Request Timeout & Response Timeout
- 逾時有請求逾時(Request Timeout):HTTP用戶端發起請求到接受到HTTP伺服器端返迴響應頭的這段時間,
如果超出設定時間,則表示請求逾時。
- 響應逾時(Response Timeout):HTTP伺服器端開始發送響應資料到HTTP用戶端接收全部資料的這段時間,
如果超出設定時間,則表示響應逾時。
範例程式碼:Timeout Demo
var http = require('http');var request_timer = null, req = null;// 請求5秒逾時request_timer = setTimeout(function() { req.abort(); console.log('Request Timeout.');}, 5000);var options = { host: 'www.google.com', port: 80, path: '/'};req = http.get(options, function(res) { clearTimeout(request_timer); // 等待響應60秒逾時 var response_timer = setTimeout(function() { res.destroy(); console.log('Response Timeout.'); }, 60000); console.log("Got response: " + res.statusCode); var chunks = [], length = 0; res.on('data', function(chunk) { length += chunk.length; chunks.push(chunk); }); res.on('end', function() { clearTimeout(response_timer); var data = new Buffer(length); // 延後copy for(var i=0, pos=0, size=chunks.length; i
有愛
^_^ 希望本文對你有用。