Chuyển đến nội dung chính

第 7 課:API 閘道模式 — Kong、APISIX 與 Envoy

什麼是 API 閘道、功能(路由、驗證、速率限制、協定轉換)、比較 Kong、APISIX、Envoy、Traefik、前端後端 (BFF) 模式、在 Kubernetes 上設定 API 閘道。

🏗️ 建築 — 第 7 課 第 7 課:API 閘道模式 — Kong、APISIX &特使

雲端原生微服務架構

第 2 部分:微服務設計與通訊模式

亞洲開發網

第 7 課:API 閘道模式 — Kong、APISIX 與 Envoy

簡介

當系統有10個、50個、100個微服務時,客戶端無法直接呼叫每個服務。 API 閘道充當單一入口點,集中處理橫切問題。


1.為什麼需要API網關?

1.1 沒有網關的問題

❌ Client gọi trực tiếp:
Mobile App ──▶ Order Service (https://order.internal:8080)
           ──▶ Payment Service (https://payment.internal:8081)
           ──▶ User Service (https://user.internal:8082)
           ──▶ Catalog Service (https://catalog.internal:8083)

Vấn đề:
├── Client cần biết địa chỉ từng service
├── Mỗi service tự implement auth, rate limit, CORS
├── Thay đổi service address → update client
├── Không có single point để monitor traffic
└── Security: expose internal services ra internet

1.2 API網關解決方案

✅ Single entry point:
Mobile App ──▶ API Gateway (https://api.example.com)
                   │
                   ├──▶ /orders   → Order Service
                   ├──▶ /payments → Payment Service
                   ├──▶ /users    → User Service
                   └──▶ /products → Catalog Service

Gateway xử lý tập trung:
├── Authentication (JWT validation)
├── Rate Limiting
├── Request Routing
├── Protocol Translation
├── Response Caching
├── Logging & Metrics
└── CORS, Compression

2. 詳細功能

2.1 請求路由

# Kong declarative config
services:
  - name: order-service
    url: http://order-service.services-prod:8080
    routes:
      - name: order-routes
        paths:
          - /api/v1/orders
        methods:
          - GET
          - POST
        strip_path: false

  - name: payment-service
    url: http://payment-service.services-prod:8080
    routes:
      - name: payment-routes
        paths:
          - /api/v1/payments

2.2 身份驗證

Client ──Bearer Token──▶ API Gateway
                              │
                         JWT Validation:
                         ├── Verify signature (RS256/ES256)
                         ├── Check expiration
                         ├── Validate issuer
                         └── Extract claims (user_id, roles, tenant_id)
                              │
                         Forward headers:
                         X-User-ID: usr-042
                         X-Roles: admin,editor
                         X-Tenant-ID: tenant-001
                              │
                              ▼
                         Downstream Service
                         (trust gateway headers)

2.3 速率限制

Rate Limiting Strategies:

Per User:
  user-A: 100 requests / minute
  user-B: 100 requests / minute

Per API:
  GET /orders:  1000 requests / minute
  POST /orders: 100 requests / minute

Per Service Plan:
  Free tier:  60 requests / minute
  Pro tier:   600 requests / minute
  Enterprise: 6000 requests / minute

Response khi exceed:
  HTTP 429 Too Many Requests
  Retry-After: 30
  X-RateLimit-Limit: 100
  X-RateLimit-Remaining: 0
  X-RateLimit-Reset: 1711872000

2.4 協定翻譯

Browser (REST/JSON) ──▶ API Gateway ──▶ gRPC Service
                              │
                     Translate:
                     - JSON → Protobuf
                     - HTTP/1.1 → HTTP/2
                     - REST method → gRPC method

WebSocket ──▶ API Gateway ──▶ Streaming Service
GraphQL   ──▶ API Gateway ──▶ REST Services (aggregation)

3. 比較網關解決方案

特點孔APISIX特使特拉菲克
核心Nginx + LuaNginx + LuaC++去
設定儲存PostgreSQL等xDS API檔/K8s
插件系統Lua/Go/JSLua/Java/Go/WASMC++/WASM去中間件
效能曹非常高非常高曹
K8s 原生Kong 入口控制器APISIX 入口特使閘道Traefik 入口
服務網格孔網—Istio 資料平面Traefik 網格
管理介面孔經理(企業)儀表板(免費)—儀表板
學習曲線平均平均曹低
最適合企業級,插件豐富高效能服務網格K8s自動發現

3.1 建議

Startup / Small team:
  → Traefik (auto-discovery, Let's Encrypt built-in)

Medium / High performance:
  → APISIX (etcd-backed, hot reload, dashboard free)

Enterprise / Plugin-rich:
  → Kong (mature ecosystem, enterprise support)

Service Mesh integration:
  → Envoy (Istio data plane, xDS API)

AWS ecosystem:
  → AWS API Gateway + ALB

4.前端後端(BFF)模式

當客戶端類型(Web、行動、物聯網)需要 不同的 API 時:

┌──────────┐   ┌──────────────┐
│   Web    │──▶│  Web BFF     │──┐
│  Browser │   │ (REST, rich) │  │
└──────────┘   └──────────────┘  │
                                  │
┌──────────┐   ┌──────────────┐  │    ┌──────────────┐
│  Mobile  │──▶│ Mobile BFF   │──┼───▶│  Backend     │
│   App    │   │ (compact)    │  │    │  Services    │
└──────────┘   └──────────────┘  │    └──────────────┘
                                  │
┌──────────┐   ┌──────────────┐  │
│   IoT    │──▶│  IoT BFF     │──┘
│ Devices  │   │ (minimal)    │
└──────────┘   └──────────────┘

Web BFF: Trả full data, rich response
Mobile BFF: Response compact, ít fields, optimized bandwidth
IoT BFF: Minimal payload, binary protocol

5. 在 Kubernetes 上部署

5.1 Kong 入口控制器

# Cài đặt Kong qua Helm
# helm install kong kong/ingress -n gateway --create-namespace

apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: rate-limiting
config:
  minute: 100
  policy: redis
  redis_host: redis.platform
plugin: rate-limiting

---
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: jwt-auth
plugin: jwt

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-ingress
  annotations:
    konghq.com/plugins: rate-limiting, jwt-auth
    konghq.com/strip-path: "false"
spec:
  ingressClassName: kong
  tls:
    - hosts:
        - api.example.com
      secretName: api-tls
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /api/v1/orders
            pathType: Prefix
            backend:
              service:
                name: order-service
                port:
                  number: 8080
          - path: /api/v1/payments
            pathType: Prefix
            backend:
              service:
                name: payment-service
                port:
                  number: 8080

6. API 閘道反模式

❌ Business logic trong Gateway
   → Gateway chỉ xử lý cross-cutting concerns
   → Business logic thuộc về downstream services

❌ Gateway là single point of failure
   → Deploy multiple replicas + load balancer
   → Health check + auto-restart

❌ Quá nhiều aggregation trong Gateway
   → Dùng BFF pattern thay vì biến Gateway thành "God Service"

❌ Không có fallback khi downstream down
   → Implement circuit breaker tại Gateway layer
   → Trả cached response hoặc degraded response

7. 總結

概念重點
API閘道單一入口點,集中處理橫切關注點
路由將請求路由到正確的下游服務
授權JWT集中驗證,透過標頭轉發聲明
速率限制保護後端服務免受流量高峰的影響
最好的朋友每種客戶端類型都有自己的、經過優化的網關
反模式不要將業務邏輯放在網關中

下一篇文章:每個服務的資料庫和多語言持久性 - 如何管理微服務架構中的資料。