Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การสร้าง Agent ใน Node.js

ใน Node.js สามารถสร้าง instance ของ Agent ได้ด้วย new Agent() เมธอด http.request() ใช้ globalAgent จากโมดูล http เพื่อสร้าง custom http.Agent instance

ไวยากรณ์

new Agent({options})

ตัวเลือก (Options)

  • keepAlive – เก็บ socket ไว้แม้ไม่มีคำขอค้างอยู่ เพื่อนำกลับมาใช้ใหม่โดยไม่ต้องสร้าง TCP connection ใหม่ ค่าเริ่มต้น: false
  • keepAliveMsecs – ระยะหน่วงเริ่มต้นสำหรับ TCP keep-alive packets เมื่อ keepAlive เป็น true ค่าเริ่มต้น: 1000
  • maxSockets – จำนวน socket สูงสุดต่อ host ค่าเริ่มต้น: Infinity
  • maxTotalSockets – จำนวน socket สูงสุดรวมทุก host ค่าเริ่มต้น: Infinity
  • maxFreeSockets – จำนวน free socket สูงสุดที่ปล่อยให้เปิดอยู่ ค่าเริ่มต้น: 256
  • scheduling – กลยุทธ์การจัดตาราง socket: 'fifo' หรือ 'lifo'
  • timeout – socket timeout ในมิลลิวินาที

ตัวอย่าง: สร้าง Agent แบบพื้นฐาน

const http = require('http');

var agent = new http.Agent({});

const aliveAgent = new http.Agent({
  keepAlive: true,
  maxSockets: 5,
});

var aliveConnection = aliveAgent.createConnection;
var connection = agent.createConnection;

console.log('Succesfully created connection with agent: ', connection.toString);
console.log('Succesfully created connection with alive agent: ', aliveConnection.toString);

ตัวอย่าง: ใช้ agentkeepalive (แนะนำ)

โมดูล agentkeepalive ให้ความยืดหยุ่นมากกว่า

npm install agentkeepalive --save
const http = require('http');
const Agent = require('agentkeepalive');

const keepAliveAgent = new Agent({});

const options = {
  host: 'tutorialspoint.com',
  port: 80,
  path: '/',
  method: 'GET',
  agent: keepAliveAgent,
};

const req = http.request(options, (res) => {
  console.log("StatusCode: ", res.statusCode);
  console.log("Headers: ", res.headers);
});

console.log("Agent Options: ", req.agent.options);
req.end();

ผลลัพธ์ตัวอย่าง

Agent Options: { socketActiveTTL: 0, timeout: 30000, freeSocketTimeout: 15000, keepAlive: true, path: null }
StatusCode: 403
Headers: { date: '...', server: 'Apache', ... }