0Pricing
Node.js Backend Development Bootcamp · Ders

Node.js Mikroservisleri Geliştirme

Alan odaklı tasarıma odaklanarak birbiriyle iletişim kuran bağımsız Node.js servisleri oluşturun.

Node.js Mikroservisleri Geliştirme, CoddyKit'te ücretsiz bir Node.js Backend Development Bootcamp dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Node.js Backend Development Bootcamp öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Node.js Backend Development Bootcamp kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Node.js Microservices Intro

Welcome to building Node.js microservices! We'll explore how to create small, independent services that work together.

A microservice is an architectural style where an application is built as a collection of small, autonomous services, each running in its own process and communicating with lightweight mechanisms, often an HTTP API.

Node.js Mikroservisleri Geliştirme — resim 1

Core Microservice Principles

Microservices follow key principles:

  • Independent Deployment: Each service can be deployed independently.
  • Loose Coupling: Services are not tightly dependent on each other.
  • Single Responsibility: Each service focuses on a specific business capability (a 'domain').
  • Technology Diversity: Different services can use different technologies (though we'll stick to Node.js here).

Domain-Driven Design Basics

Domain-Driven Design (DDD) is crucial for microservices. It means structuring your services around business domains (e.g., 'Users', 'Products', 'Orders').

  • Bounded Contexts: Each microservice defines its own clear boundary, owning its specific domain data and logic.
  • Ubiquitous Language: Using a common language for domain concepts within that service.

Structuring a Node.js Service

A typical Node.js microservice project might have a structure like this:

  • my-service/
  •   src/
  •     controllers/ (logic for requests)
  •     models/ (data schemas)
  •     routes/ (API endpoints)
  •     app.js (main Express setup)
  •   package.json
  •   .env (environment variables)

Inter-Service Communication

Microservices need to communicate to fulfill requests. Common methods include:

  • HTTP/REST: Synchronous calls between services. One service makes an HTTP request to another.
  • Message Queues: Asynchronous communication via a message broker (e.g., RabbitMQ, Kafka). Services publish events and subscribe to others.

For this lesson, we'll focus on HTTP communication due to its simplicity.

Building a User Microservice

Let's create a simple 'Users' microservice using Express. This service will manage user data and run on port 3001.

Try running this code:

const express = require('express');
const app = express();
const PORT = 3001;

app.use(express.json());

const users = [
  { id: 'u1', name: 'Alice', email: 'alice@example.com' },
  { id: 'u2', name: 'Bob', email: 'bob@example.com' }
];

app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === req.params.id);
  if (user) {
    res.json(user);
  } else {
    res.status(404).send('User not found');
  }
});

app.get('/users', (req, res) => {
  res.json(users);
});

app.listen(PORT, () => {
  console.log(`Users Service running on port ${PORT}`);
});

Building a Product Microservice

Now, let's create a separate 'Products' microservice. This service will manage product data and run on port 3002.

This is a completely independent application:

const express = require('express');
const app = express();
const PORT = 3002;

app.use(express.json());

const products = [
  { id: 'p1', name: 'Laptop', price: 1200, ownerId: 'u1' },
  { id: 'p2', name: 'Mouse', price: 25, ownerId: 'u2' }
];

app.get('/products', (req, res) => {
  res.json(products);
});

app.listen(PORT, () => {
  console.log(`Products Service running on port ${PORT}`);
});

Simulating Service Communication

How would the 'Products' service get user details for a product's owner? It makes an HTTP call to the 'Users' service!

In this example, we simulate both a mini-server (for users) and a client (fetching user data) in one script to show the communication flow. This client part is what your Product service would do.

const http = require('http');

// --- SIMULATED USER SERVICE (SERVER PART) ---
const users = {
  'u1': { id: 'u1', name: 'Alice', email: 'alice@example.com' },
  'u2': { id: 'u2', name: 'Bob', email: 'bob@example.com' }
};

const simulatedUserServer = http.createServer((req, res) => {
  if (req.url.startsWith('/users/') && req.method === 'GET') {
    const userId = req.url.split('/')[2];
    if (users[userId]) {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(users[userId]));
    } else {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('User not found');
    }
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

const SIMULATED_PORT = 3001;
simulatedUserServer.listen(SIMULATED_PORT, () => {
  console.log(`Simulated User Service running on port ${SIMULATED_PORT}`);
});

// --- CLIENT PART (e.g., a Product Service trying to get user data) ---
async function fetchUserFromSimulatedService(userId) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: SIMULATED_PORT,
      path: `/users/${userId}`,
      method: 'GET'
    };

    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => data += chunk);
      res.on('end', () => {
        if (res.statusCode === 200) {
          resolve(JSON.parse(data));
        } else {
          reject(new Error(`Failed to fetch user: ${res.statusCode}`));
        }
      });
    });

    req.on('error', (e) => reject(e));
    req.end();
  });
}

console.log('\n--- Product Service fetching user data simulation ---');
fetchUserFromSimulatedService('u1')
  .then(user => console.log('Fetched User:', user))
  .catch(error => console.error('Error fetching user:', error.message))
  .finally(() => {
    // Important: close the simulated server after demonstration
    simulatedUserServer.close(() => console.log('Simulated User Service stopped.'));
  });

fetchUserFromSimulatedService('u3') // Try fetching a non-existent user
  .then(user => console.log('Fetched User:', user))
  .catch(error => console.error('Error fetching user:', error.message));

Microservice Trade-offs

While powerful, microservices come with trade-offs:

  • Increased Complexity: More services mean more to manage, deploy, and monitor.
  • Data Consistency: Maintaining data consistency across multiple databases can be challenging.
  • Distributed Transactions: Operations spanning multiple services require careful design.
  • Operational Overhead: Requires robust CI/CD and monitoring tools.

Quick Check: Microservice Benefits

Based on what you've learned, which of the following is a primary benefit of using a microservices architecture?

Recap & Next Steps

We've covered the basics of developing Node.js microservices, understanding their core principles, and how they communicate. We saw how to structure small, domain-focused services and even simulated inter-service communication.

While powerful, remember the trade-offs in complexity. Next, you'll learn how to manage client requests to these services using an API Gateway!

Sıkça Sorulan Sorular

“Node.js Mikroservisleri Geliştirme” dersi ücretsiz mi?

Evet — “Node.js Mikroservisleri Geliştirme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Node.js Backend Development Bootcamp kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Node.js Backend Development Bootcamp kursu toplamda 4 dersten oluşur.

“Node.js Mikroservisleri Geliştirme” dersinde ne öğreneceğim?

Alan odaklı tasarıma odaklanarak birbiriyle iletişim kuran bağımsız Node.js servisleri oluşturun. Node.js Backend Development Bootcamp ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Node.js Backend Development Bootcamp öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Node.js Backend Development Bootcamp, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Node.js Mikroservisleri Geliştirme” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Node.js Backend Development Bootcamp dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Node.js Backend Development Bootcamp dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Mikroservis Mimarilerine Giriş
  2. Node.js Mikroservisleri Geliştirme
  3. API Ağ Geçidi Uygulama
  4. Mesaj Kuyruklarıyla Hizmetler Arası İletişim
← Node.js Backend Development Bootcamp Sayfasına Dön