Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

Node.js에서 HTTP 에이전트(Agent) 생성하는 방법

Node.js에서는 new Agent() 메서드를 사용하여 에이전트 인스턴스를 생성할 수 있습니다. 기본적으로 http.request() 메서드는 'http' 모듈의 globalAgent를 사용하지만, 필요에 따라 직접 커스텀 http.Agent 인스턴스를 만들어 연결 동작을 세밀하게 제어할 수 있습니다.

문법(Syntax)

new Agent({options})

매개변수(Parameters)

위 함수는 생성 시 에이전트에 적용할 다음과 같은 옵션(options)을 받을 수 있습니다.

  • keepAlive – 처리 중인 요청이 없더라도 소켓을 유지하여, 이후 요청 시 TCP 연결을 다시 맺지 않고 재사용할 수 있게 합니다. 연결을 닫으려면 'close' 이벤트를 사용합니다. 기본값: false

  • keepAliveMsecskeepAlive 옵션이 true일 때, TCP Keep-Alive 패킷 전송의 초기 지연 시간(밀리초)을 정의합니다. 기본값: 1000

  • maxSockets – 호스트(host) 하나당 허용되는 최대 소켓 수를 정의합니다. 기본값: 무제한(Infinity)

  • maxTotalSockets – 모든 호스트에 대해 허용되는 총 소켓 수입니다. 각 요청은 한도에 도달할 때까지 새로운 소켓을 사용합니다. 기본값: Infinity

  • maxFreeSockets – 유휴(free) 상태로 열려 있을 수 있는 최대 소켓 수입니다. 기본값: 256

  • scheduling – 다음 유휴 소켓을 선택할 때 적용되는 스케줄링 전략으로, 'fifo'(선입선출) 또는 'lifo'(후입선출) 중 하나를 지정할 수 있습니다.

  • timeout – 소켓 타임아웃을 밀리초 단위로 나타냅니다.

예제 1: 기본 에이전트 생성

agent.js라는 이름의 파일을 생성하고 아래 코드를 복사한 뒤, 다음 명령어로 실행해 보세요.

node agent.js

agent.js

// 새로운 Agent 생성 과정을 보여주는 Node.js 프로그램

// http 모듈 불러오기
const http = require('http');

// 새로운 에이전트 생성
var agent = new http.Agent({});

// keepAlive 옵션을 적용한 에이전트 생성
const aliveAgent = new http.Agent({
    keepAlive: true, maxSockets: 5,
});

// alive agent로 연결 생성
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);

실행 결과(Output)

C:\home\node>> node agent.js
Succesfully created connection with agent: function toString() { [native code] }
Succesfully created connection with alive agent: function toString() { [native code] }

예제 2: agentkeepalive 모듈 활용하기

agentkeepalive 모듈은 소켓이나 에이전트를 생성할 때 더욱 유연한 설정을 제공합니다. 아래 예제에서 이 모듈을 사용해 보겠습니다.

설치(Installation)

npm install agentkeepalive --save

프로그램 코드(Program Code)

// 새로운 Agent 생성 과정을 보여주는 Node.js 프로그램

// http 모듈 불러오기
const http = require('http');
// agentkeepalive 모듈 불러오기
const Agent = require('agentkeepalive');

// 새로운 keep-alive 에이전트 생성
const keepAliveAgent = new Agent({});

// 요청 옵션 구성
const options = {
    host: 'tutorialspoint.com',
    port: 80,
    path: '/',
    method: 'GET',
    agent: keepAliveAgent,
};

// http 서버 모듈을 통해 상세 정보 요청
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();

실행 결과(Output)

C:\home\node>> node agent.js
Agent Options: { socketActiveTTL: 0,
    timeout: 30000,
    freeSocketTimeout: 15000,
    keepAlive: true,
    path: null }
StatusCode: 403
Headers: { date: 'Sun, 25 Apr 2021 08:21:14 GMT',
    server: 'Apache',
    'x-frame-options': 'SAMEORIGIN',
    'last-modified': 'Thu, 16 Oct 2014 13:20:58 GMT',
    etag: '"1321-5058a1e728280"',
    'accept-ranges': 'bytes',
    'content-length': '4897',
    'x-xss-protection': '1; mode=block',
    vary: 'User-Agent',
    'keep-alive': 'timeout=5, max=100',
    connection: 'Keep-Alive',
    'content-type': 'text/html; charset=UTF-8' }

위 실행 결과에서 확인할 수 있듯이, agentkeepalive 모듈은 timeout, freeSocketTimeout 등 추가적인 옵션을 제공하며, Keep-Alive 연결을 효율적으로 관리하여 네트워크 성능을 향상시킬 수 있습니다.