Nodejs學習記錄:http模塊

概覽

http模塊源碼: https://github.com/nodejs/nod...


function createServer(opts, requestListener) {
  return new Server(opts, requestListener);
}

function request(url, options, cb) {
  return new ClientRequest(url, options, cb);
}

function get(url, options, cb) {
  var req = request(url, options, cb);
  req.end();
  return req;
}

我們不難發現,http 模塊提供三個主要的函數: http.request, http.get, http.createServer。前兩個函數主要是爲了創建 http 客戶端,向其它服務器發送請求,http.get 只是 http.request 的發送 get 請求的便捷方式;而 http.createServer 是爲了創建 Node 服務,比如 Koa 服務框架就是基於 http.createServer 封裝的。

http.Agent

http.Agent 主要是爲 http.request, http.get 提供代理服務的,用於管理 http 連接的創建,銷燬及複用工作。http.request, http.get 默認使用 http.globalAgent 作爲代理,每次請求都是“建立連接-數據傳輸-銷燬連接”的過程,如果我們想讓多個請求複用同一個 connection,則需要重新定義 agent 去覆蓋默認的 http.globalAgent,下面我們看一下新建一個agent的需要哪些主要參數:

  • keepAlive:{Boolean} 是否開啓 keepAlive,多個請求公用一個 socket connection,默認是 false。
  • maxSockets:{Number} 每臺主機允許的socket的最大值,默認值爲Infinity。
  • maxFreeSockets:{Number} 處於連接池空閒狀態的最大連接數, 僅當開啓 keepAlive 纔有效。
let http = require('http');
const keepAliveAgent = new http.Agent({ 
    keepAlive: true,
    maxScokets: 1000,
    maxFreeSockets: 50 
})
http.get({
  hostname: 'localhost',
  port: 80,
  path: '/',
  agent: keepAliveAgent 
}, (res) => {
  // Do stuff with response
});

只有向相同的 host 和 port 發送請求才能公用同一個 keepAlive 的 socket 連接,如果開啓 keepAlive ,同一時間內多個請求會被放在隊列裏等待;如果當前隊列爲空,該 socket 處於空閒狀態,但是不會被銷燬,等待下一次請求的到來。

使用 keepAlive 代理,有效的減少了建立/銷燬連接的開銷,開發者可以對連接池進行動態管理。

大體差不多就是這個意思,詳細可以看Node.js 官方文檔

參考

https://nodejs.org/docs/lates...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章