Skip to content

nguyenvanro/microservices_fastapi

Repository files navigation

FastAPI Microservices

📋 Tổng quan

Hệ thống microservices bao gồm:

  • User Service (Port 8001): Quản lý người dùng
  • Product Service (Port 8002): Quản lý sản phẩm
  • Order Service (Port 8003): Quản lý đơn hàng
  • API Gateway (Port 8000): Điểm truy cập duy nhất cho client

🚀 Cách 1: Chạy với Docker Compose (Khuyến nghị)

Bước 1: Cài đặt Docker và Docker Compose

# Kiểm tra Docker đã cài đặt
docker --version
docker-compose --version

Bước 2: Build và chạy tất cả services

# Build tất cả services
docker-compose build

# Chạy tất cả services
docker-compose up -d

# Xem logs
docker-compose logs -f

# Kiểm tra trạng thái
docker-compose ps

Bước 3: Kiểm tra services đang chạy

# API Gateway
curl http://localhost:8000/

# Health check
curl http://localhost:8000/health

Dừng services

# Dừng tất cả
docker-compose down

# Dừng và xóa volumes (xóa dữ liệu)
docker-compose down -v

🔧 Cách 2: Chạy trực tiếp (Development)

Bước 1: Cài đặt dependencies cho từng service

# User Service
cd user-service
pip install -r requirements.txt

# Product Service
cd ../product-service
pip install -r requirements.txt

# Order Service
cd ../order-service
pip install -r requirements.txt

# API Gateway
cd ../api-gateway
pip install -r requirements.txt

Bước 2: Chạy từng service trong terminal riêng

Terminal 1 - User Service:

cd user-service
uvicorn app.main:app --reload --port 8001

Terminal 2 - Product Service:

cd product-service
uvicorn app.main:app --reload --port 8002

Terminal 3 - Order Service:

cd order-service
export USER_SERVICE_URL=http://localhost:8001
export PRODUCT_SERVICE_URL=http://localhost:8002
uvicorn app.main:app --reload --port 8003

Terminal 4 - API Gateway:

cd api-gateway
export USER_SERVICE_URL=http://localhost:8001
export PRODUCT_SERVICE_URL=http://localhost:8002
export ORDER_SERVICE_URL=http://localhost:8003
uvicorn app.main:app --reload --port 8000

📝 Test API

Sử dụng script test tự động

python test_api.py

Test thủ công với curl

1. Tạo User:

curl -X POST http://localhost:8000/api/users/ \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john_doe",
    "email": "john@example.com",
    "full_name": "John Doe",
    "password": "secret123"
  }'

2. Login:

curl -X POST http://localhost:8000/api/users/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john_doe",
    "password": "secret123"
  }'

3. Tạo Product:

curl -X POST http://localhost:8000/api/products/ \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Laptop Dell XPS 13",
    "description": "Laptop cao cấp",
    "price": 25000000,
    "stock": 10,
    "category": "Electronics"
  }'

4. Lấy danh sách Products:

curl http://localhost:8000/api/products/

5. Tạo Order:

curl -X POST http://localhost:8000/api/orders/ \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": 1,
    "items": [
      {"product_id": 1, "quantity": 2}
    ]
  }'

6. Lấy Orders của User:

curl "http://localhost:8000/api/orders/?user_id=1"

📚 API Documentation

Sau khi chạy services, truy cập Swagger UI:

🏗️ Kiến trúc Microservices

┌─────────────┐
│   Client    │
└──────┬──────┘
       │
       ▼
┌─────────────────┐
│  API Gateway    │ (Port 8000)
│  Routing Layer  │
└────────┬────────┘
         │
    ┌────┴────┬────────┬────────┐
    ▼         ▼        ▼        ▼
┌────────┐ ┌────────┐ ┌────────┐
│  User  │ │Product │ │ Order  │
│Service │ │Service │ │Service │
│ :8001  │ │ :8002  │ │ :8003  │
└───┬────┘ └───┬────┘ └───┬────┘
    │          │          │
    └──────────┴──────────┘
               │
         ┌─────▼──────┐
         │ PostgreSQL │
         │   Redis    │
         └────────────┘

🔍 Monitoring và Logging

Xem logs của từng service

# Tất cả services
docker-compose logs -f

# Một service cụ thể
docker-compose logs -f user-service
docker-compose logs -f product-service
docker-compose logs -f order-service
docker-compose logs -f api-gateway

🛠️ Các tính năng nâng cao có thể thêm

  1. Authentication & Authorization

    • JWT tokens
    • OAuth2
    • Role-based access control
  2. Message Queue

    • RabbitMQ hoặc Kafka
    • Event-driven architecture
    • Async communication giữa services
  3. Caching

    • Redis caching
    • Response caching
    • Database query caching
  4. Service Discovery

    • Consul
    • Eureka
  5. Load Balancing

    • Nginx
    • HAProxy
  6. Monitoring

    • Prometheus + Grafana
    • ELK Stack (Elasticsearch, Logstash, Kibana)
  7. Circuit Breaker Pattern

    • Resilient communication
    • Fallback mechanisms

🐛 Troubleshooting

Lỗi: Port đã được sử dụng

# Tìm và kill process đang dùng port
lsof -i :8000  # Mac/Linux
netstat -ano | findstr :8000  # Windows

Lỗi: Service không kết nối được

# Kiểm tra network
docker-compose exec user-service ping product-service

Reset toàn bộ database

docker-compose down -v
docker-compose up -d

📖 Tài liệu tham khảo

👨‍💻 Phát triển tiếp

Bạn có thể mở rộng hệ thống bằng cách:

  1. Thêm services mới (Payment, Notification, etc.)
  2. Implement API versioning
  3. Thêm unit tests và integration tests
  4. Setup CI/CD pipeline
  5. Deploy lên cloud (AWS, GCP, Azure)

Happy Coding! 🚀

About

Microservices Fastapi

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors