[nodejs] Node.js를 사용한 마이크로서비스 통신 방법

마이크로서비스 아키텍처는 여러 개의 작은 서비스로 애플리케이션을 구성하고, 이러한 서비스들이 서로 통신하여 전체 시스템을 형성합니다. Node.js는 이러한 마이크로서비스 아키텍처에서 효과적으로 사용될 수 있는데, 이 기술 블로그에서는 Node.js를 사용하여 마이크로서비스 간에 효과적으로 통신하는 방법에 대해 살펴봅니다.

내부 통신

HTTP 통신

마이크로서비스는 주로 HTTP를 사용하여 통신합니다. Node.js에서는 내장된 http 또는 axios와 같은 외부 라이브러리를 사용하여 HTTP 통신을 구현할 수 있습니다.

const http = require('http');

const options = {
  hostname: 'target-service',
  port: 80,
  path: '/endpoint',
  method: 'GET'
};

const req = http.request(options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    // 처리된 데이터 사용
    console.log(data);
  });
});

req.on('error', (e) => {
  console.error(`문제 발생: ${e.message}`);
});

req.end();

gRPC

Google에서 개발한 gRPC는 HTTP/2를 기반으로 하는 고성능 RPC 프레임워크입니다. Node.js에서는 grpc 모듈을 사용하여 gRPC 통신을 구현할 수 있습니다.

const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');

const packageDefinition = protoLoader.loadSync('path/to/your/protofile.proto');
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
const myService = protoDescriptor.MyService;

const client = new myService('target-service:50051', grpc.credentials.createInsecure());

client.makeCall({/* 요청 데이터 */}, (err, response) => {
  if (err) {
    console.error('에러:', err);
  } else {
    // 응답 처리
    console.log('응답:', response);
  }
});

외부 통신

RabbitMQ

메시지 브로커로써 RabbitMQ를 사용하여 마이크로서비스 간에 안정적으로 통신할 수 있습니다. Node.js에서는 amqplib 모듈을 사용하여 RabbitMQ와 통신할 수 있습니다.

const amqp = require('amqplib');

async function main() {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();

  const queueName = 'my-queue';

  channel.assertQueue(queueName, { durable: true });
  channel.sendToQueue(queueName, Buffer.from('hello world'));

  console.log('메시지 전송: "hello world"');

  channel.consume(queueName, (msg) => {
    console.log('메시지 수신:', msg.content.toString());
  }, { noAck: true });
}

main();

위의 예제에서는 RabbitMQ를 사용하여 메시지를 보내고 받는 방법을 보여줍니다.

Node.js를 사용한 마이크로서비스 간 통신은 다양한 방법으로 가능하며, 이러한 방법을 잘 이해하고 활용함으로써 안정적이고 효율적인 마이크로서비스 아키텍처를 구축할 수 있습니다.

참고 자료