feat(docs): Streamline Vietnamese documentation with updated diagrams and sections

- Enhanced Mermaid diagrams for better visual clarity and consistency across guides.
- Added new sections on caching, data consistency, and observability patterns to the architecture documentation.
- Improved formatting and structure to align with the English version, ensuring a cohesive user experience.
- Removed outdated service communication documentation to reduce clutter and focus on relevant content.
This commit is contained in:
Ho Ngoc Hai
2026-01-12 12:31:55 +07:00
parent ec59262411
commit 1e22e83879
4 changed files with 986 additions and 0 deletions

View File

@@ -0,0 +1,279 @@
# Template Microservice .NET 10
> Template microservice .NET 10 cấp doanh nghiệp theo các pattern DDD, CQRS và Clean Architecture.
## Tổng Quan
Template này cung cấp cấu trúc sẵn sàng production cho microservices .NET dựa trên kiến trúc tham chiếu eShopOnContainers với:
- **Domain-Driven Design (DDD)** - Aggregates, Entities, Value Objects, Domain Events
- **CQRS Pattern** - Tách biệt Commands (ghi) và Queries (đọc) với MediatR
- **Clean Architecture** - Phân tầng Domain, Infrastructure, API
- **EF Core 10** - PostgreSQL với connection resilience
- **FluentValidation** - Validation request
- **API Versioning** - Versioning theo URL segment
- **Health Checks** - Probes sẵn sàng cho Kubernetes
- **Structured Logging** - Serilog với console và Seq
## Yêu Cầu
| Yêu cầu | Phiên bản |
|---------|-----------|
| .NET SDK | 10.0.101+ |
| Docker | 24.0+ |
| PostgreSQL | 15+ (hoặc dùng Docker) |
## Bắt Đầu Nhanh
### 1. Tạo Service Mới
```bash
# Sao chép template sang service mới
cp -r services/_template_dot_net services/your-service-name
cd services/your-service-name
# Đổi tên tất cả "MyService" thành "YourService"
find . -type f -name "*.cs" -exec sed -i '' 's/MyService/YourService/g' {} +
find . -type f -name "*.csproj" -exec sed -i '' 's/MyService/YourService/g' {} +
```
### 2. Cấu Hình Môi Trường
```bash
cp .env.example .env
nano .env
```
### 3. Chạy với Docker
```bash
docker-compose up -d
docker-compose logs -f myservice-api
```
### 4. Chạy Local
```bash
dotnet restore
dotnet build
dotnet run --project src/MyService.API
```
## Cấu Trúc Dự Án
```
_template_dot_net/
├── src/
│ ├── MyService.API/ # Lớp Presentation (Controllers, CQRS)
│ │ ├── Controllers/ # Các API endpoints
│ │ ├── Application/ # Triển khai CQRS
│ │ │ ├── Commands/ # Thao tác ghi (MediatR)
│ │ │ ├── Queries/ # Thao tác đọc
│ │ │ ├── Behaviors/ # MediatR pipeline behaviors
│ │ │ └── Validations/ # FluentValidation validators
│ │ └── Program.cs # Điểm vào ứng dụng
│ │
│ ├── MyService.Domain/ # Lớp Domain (Business logic thuần túy)
│ │ ├── AggregatesModel/ # Aggregate roots và entities
│ │ ├── Events/ # Domain events
│ │ ├── Exceptions/ # Domain exceptions
│ │ └── SeedWork/ # Base classes
│ │
│ └── MyService.Infrastructure/ # Lớp Infrastructure
│ ├── EntityConfigurations/ # Cấu hình EF Core
│ ├── Repositories/ # Triển khai repositories
│ └── MyServiceContext.cs # DbContext với Unit of Work
├── tests/
│ ├── MyService.UnitTests/ # Unit tests
│ └── MyService.FunctionalTests/ # Integration tests
├── Dockerfile # Multi-stage Docker build
└── docker-compose.yml # Thiết lập phát triển local
```
## Kiến Trúc
```mermaid
graph TB
subgraph "Lớp API"
C[Controllers]
CMD[Commands]
Q[Queries]
B[Behaviors]
V[Validations]
end
subgraph "Lớp Domain"
AR[Aggregate Roots]
E[Entities]
VO[Value Objects]
DE[Domain Events]
end
subgraph "Lớp Infrastructure"
DB[(PostgreSQL)]
R[Repositories]
CTX[DbContext]
end
C --> CMD
C --> Q
CMD --> B --> V
CMD --> AR
Q --> R
R --> CTX --> DB
style C fill:#4a90d9,stroke:#2d5986,color:#fff
style AR fill:#50c878,stroke:#2d8659,color:#fff
style DB fill:#ff6b6b,stroke:#c0392b,color:#fff
```
## Trách Nhiệm Các Lớp
### 1. Lớp Domain
- **ZERO** phụ thuộc bên ngoài (ngoại trừ MediatR.Contracts)
- Chỉ chứa các class POCO
- Triển khai các tactical patterns của DDD
| Thành phần | Mục Đích |
|------------|----------|
| **SeedWork** | Base classes: Entity, ValueObject, IAggregateRoot |
| **AggregatesModel** | Aggregate roots với entities và value objects |
| **Events** | Domain events cho giao tiếp cross-aggregate |
| **Exceptions** | Domain exceptions |
### 2. Lớp Infrastructure
- Truy cập database (EF Core)
- Triển khai repositories
- Tích hợp external services
### 3. Lớp API
- Controllers để xử lý HTTP
- Commands cho các thao tác ghi
- Queries cho các thao tác đọc
- MediatR behaviors cho cross-cutting concerns
## Pattern CQRS
### Commands (Thao Tác Ghi)
```csharp
public record CreateSampleCommand(string Name, string? Description)
: IRequest<CreateSampleCommandResult>;
public class CreateSampleCommandHandler : IRequestHandler<CreateSampleCommand, CreateSampleCommandResult>
{
public async Task<CreateSampleCommandResult> Handle(CreateSampleCommand request, CancellationToken ct)
{
var sample = new Sample(request.Name, request.Description);
_repository.Add(sample);
await _repository.UnitOfWork.SaveEntitiesAsync(ct);
return new CreateSampleCommandResult(sample.Id);
}
}
```
### Pipeline MediatR
```
Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response
```
## Các API Endpoints
| Method | Endpoint | Mô Tả |
|--------|----------|-------|
| `GET` | `/api/v1/samples` | Lấy tất cả samples |
| `GET` | `/api/v1/samples/{id}` | Lấy sample theo ID |
| `POST` | `/api/v1/samples` | Tạo sample mới |
| `PUT` | `/api/v1/samples/{id}` | Cập nhật sample |
| `DELETE` | `/api/v1/samples/{id}` | Xóa sample |
| `PATCH` | `/api/v1/samples/{id}/status` | Thay đổi trạng thái |
### Health Endpoints
| Endpoint | Mục Đích |
|----------|----------|
| `/health` | Trạng thái health đầy đủ |
| `/health/live` | Kiểm tra sống |
| `/health/ready` | Kiểm tra sẵn sàng |
## Biến Môi Trường
| Biến | Mô Tả | Mặc định |
|------|-------|----------|
| `ASPNETCORE_ENVIRONMENT` | Tên môi trường | `Development` |
| `DATABASE_URL` | Kết nối PostgreSQL | - |
| `REDIS_URL` | Kết nối Redis | - |
| `JWT_SECRET` | Secret ký JWT | - |
## Kiểm Thử
```bash
# Chạy tất cả tests
dotnet test
# Chạy với coverage
dotnet test /p:CollectCoverage=true /p:CoverageReportFormat=cobertura
# Chạy project test cụ thể
dotnet test tests/MyService.UnitTests
```
## Triển Khai
### Docker Build
```bash
docker build -t myservice:latest .
docker run -p 5000:8080 --env-file .env myservice:latest
```
### Kubernetes
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myservice-api
spec:
replicas: 3
template:
spec:
containers:
- name: api
image: myservice:latest
livenessProbe:
httpGet:
path: /health/live
port: 8080
readinessProbe:
httpGet:
path: /health/ready
port: 8080
```
## Có Gì Mới Trong .NET 10
- Tính năng ngôn ngữ **C# 14**
- Hỗ trợ **Native AOT** được cải thiện
- Hiệu suất **async/await** tốt hơn
- **JSON serialization** được nâng cao
- Hỗ trợ **LTS** 3 năm (đến tháng 11/2028)
## Tài Liệu Liên Quan
- [Chi Tiết Kiến Trúc](../architecture/microservices-communication.md)
- [DDD Patterns](../architecture/system-design.md)
- [Hướng Dẫn Triển Khai](../guides/deployment.md)
## Tài Nguyên
- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers)
- [Tài liệu .NET 10](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10)
- [MediatR](https://github.com/jbogard/MediatR)
- [FluentValidation](https://docs.fluentvalidation.net/)

View File

@@ -0,0 +1,214 @@
# Template Microservice Node.js
> Template chuẩn để tạo các microservice mới trong hệ sinh thái @goodgo sử dụng Node.js/TypeScript.
## Tổng Quan
Template này cung cấp nền tảng hoàn chỉnh, sẵn sàng production để xây dựng các microservice với:
- **Framework**: Express.js với TypeScript
- **Database**: Prisma ORM với PostgreSQL
- **Validation**: Zod cho validation biến môi trường và đầu vào
- **Observability**: Prometheus metrics, logging có cấu trúc, tích hợp OpenTelemetry/Jaeger
- **Resilience**: Graceful shutdown, rate limiting (Redis), circuit breaker, health checks
- **Caching**: Chiến lược caching với Redis
- **Security**: Đã cấu hình Helmet & CORS
## Cấu Trúc Dự Án
```
src/
├── config/ # Cấu hình & Validate biến môi trường
├── middlewares/ # Express middlewares (error, logger, metrics)
├── modules/ # Feature modules (controller, service, repository)
├── routes/ # Định nghĩa API routes
└── main.ts # Entry point & App bootstrapping
```
## Bắt Đầu
### Yêu Cầu
- Node.js >= 20
- pnpm
- Docker (yêu cầu Redis)
### Cài Đặt
1. **Clone & Cài đặt dependencies**:
```bash
pnpm install
```
2. **Khởi động infrastructure**:
```bash
cd deployments/local
docker-compose up -d redis
```
3. **Thiết lập database**:
```bash
pnpm prisma migrate dev
pnpm prisma db seed
```
4. **Khởi động development server**:
```bash
pnpm dev
```
## Kiến Trúc
### Kiến Trúc Phân Lớp
```mermaid
graph TD
Request[HTTP Request] --> Middleware[Middleware Chain]
subgraph SingleService[Ranh Giới Service]
Middleware --> Correlation[Correlation ID]
Correlation --> Auth[Authentication]
Auth --> Validation[Validation]
Validation --> Error[Error Handler]
Error --> Logger[Request Logger]
Logger --> Metrics[Metrics Collector]
Metrics --> Router[Router Layer]
Router --> Controller[Controller Layer]
Controller --> Service[Service Layer]
Service --> Repository[Repository Layer]
Repository --> Database[(PostgreSQL)]
Service --> Cache[(Redis)]
end
style Correlation fill:#e1f5fe
style Auth fill:#f3e5f5
style Validation fill:#e8f5e8
```
### Chuỗi Middleware
1. **Correlation Middleware**: Tạo/truyền correlation và request IDs
2. **Authentication Middleware**: Xác thực JWT tokens
3. **Validation Middleware**: Validate dữ liệu đầu vào với Zod schemas
4. **Error Handler**: Bắt và format lỗi
5. **Logger Middleware**: Ghi log request/response
6. **Metrics Middleware**: Thu thập Prometheus metrics
### Pattern Controller → Service → Repository
- **Controller**: Xử lý HTTP requests, điều phối services
- **Service**: Chứa business logic, độc lập với HTTP
- **Repository**: Trừu tượng hóa thao tác database với Prisma
## Các API Endpoints
### Health Endpoints
| Endpoint | Mục Đích |
|----------|----------|
| `/health` | Trạng thái health đầy đủ |
| `/health/live` | Kiểm tra sống |
| `/health/ready` | Kiểm tra sẵn sàng |
### Quản Lý Feature
| Method | Endpoint | Mô Tả |
|--------|----------|-------|
| `GET` | `/api/v1/features` | Lấy tất cả features |
| `GET` | `/api/v1/features/{id}` | Lấy feature theo ID |
| `POST` | `/api/v1/features` | Tạo feature (admin) |
| `PUT` | `/api/v1/features/{id}` | Cập nhật feature |
| `DELETE` | `/api/v1/features/{id}` | Xóa feature |
| `PATCH` | `/api/v1/features/{id}/toggle` | Chuyển đổi trạng thái |
## Định Dạng Response
```json
{
"success": true,
"data": { ... },
"message": "Hoạt động hoàn thành",
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
## Biến Môi Trường
| Biến | Mô Tả | Bắt buộc |
|------|-------|----------|
| `PORT` | Cổng server | Không (mặc định: 5000) |
| `DATABASE_URL` | Kết nối PostgreSQL | **Có** |
| `REDIS_URL` | Kết nối Redis | Không |
| `JWT_SECRET` | Khóa bí mật JWT | **Có** |
| `TRACING_ENABLED` | Bật Jaeger tracing | Không |
## Tích Hợp Nền Tảng
### Thêm vào docker-compose.yml
```yaml
services:
your-service:
build:
context: ../..
dockerfile: services/your-service/Dockerfile
labels:
- "traefik.enable=true"
- "traefik.http.routers.your-service.rule=PathPrefix(`/api/v1/your-service`)"
- "traefik.http.services.your-service.loadbalancer.server.port=5002"
```
### Điểm Truy Cập
- **API**: http://localhost/api/v1/your-service
- **Health**: http://localhost/api/v1/your-service/health
- **API Docs**: http://localhost/api/v1/your-service/api-docs
- **Traefik Dashboard**: http://localhost:8080
## Kiểm Thử
```bash
# Chạy tất cả tests
pnpm test
# Chạy với coverage
pnpm test:coverage
# Chạy E2E tests
pnpm test:e2e
```
## Docker
```bash
# Build image
docker build -t your-service:latest .
# Chạy container
docker run -p 5000:5000 --env-file .env your-service:latest
```
## Tạo Service Mới
1. Sao chép template:
```bash
cp -r services/_template_nodejs services/your-service-name
```
2. Cập nhật tên trong `package.json`
3. Cấu hình môi trường trong `deployments/local/.env.local`
4. Cập nhật Prisma schema và chạy migrations
5. Triển khai modules trong `src/modules/`
6. Đăng ký trong `deployments/local/docker-compose.yml`
## Tài Liệu Liên Quan
- [Chi Tiết Kiến Trúc](../architecture/microservices-communication.md)
- [Tiêu Chuẩn Thiết Kế API](../guides/api-design.md)
- [Patterns Kiểm Thử](../guides/testing.md)