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

第 18 課:API Gateway — Kong、APISIX 與 Envoy 實戰

API網關:為什麼需要它,主要功能。比較 Kong、APISIX、Envoy Gateway 和 AWS API Gateway。設定身份驗證、速率限制、路由、負載平衡。聲明式配置和 GitOps。

🏗️ 建築 — 第 18 課 第 18 課:API 閘道 — Kong、APISIX 與 Envoy 實戰

微服務與微前端系統設計-從基礎到生產

第 6 部分:API 閘道和 BFF 層

亞洲開發網

簡介

API 閘道是來自前端的所有 API 呼叫的單一入口點。它處理跨領域的問題:身份驗證、速率限制、路由、監控——幫助微服務專注於業務邏輯。

API 閘道 — 所有要求的單一入口點


1.為什麼需要API網關?

1.1 無網關

❌ Client gọi trực tiếp services:

Frontend ──► User Service    (port 8001)
         ──► Product Service (port 8002)
         ──► Order Service   (port 8003)
         ──► Cart Service    (port 8004)

Vấn đề:
- Frontend phải biết địa chỉ từng service
- Mỗi service tự implement auth, rate limit, CORS
- Không có single point for monitoring/logging
- Service addresses thay đổi → frontend phải update

1.2 使用API網關

✅ Single entry point:

Frontend ──► API Gateway (/api/*) ──► User Service
                                  ──► Product Service
                                  ──► Order Service

API Gateway handles:
├── Authentication (JWT verification)
├── Rate Limiting (100 req/min per user)
├── Routing (path-based → service)
├── Load Balancing (round-robin)
├── SSL Termination
├── CORS
├── Request/Response transformation
└── Monitoring & Logging

2. 比較 API 網關

特點孔APISIX特使網關AWS API GW
核心Nginx/OpenRestyNginx/etcd特使代理人管理
性能高非常高非常高高
插件100+80+透過過濾器AWS 原生
K8s 原生金剛入口APISIX 入口K8s 閘道器 API不適用
設定資料庫/宣告式etcd/YAMLK8s CRD控制台/CF
儀表板孔經理阿帕契儀表板不適用控制台
成本開源開源開源按請求付費
最適合一般高性能,中國K8s原生AWS 生態系統

3. Kong配置

3.1 宣告式設定 (kong.yml)

_format_version: "3.0"

services:
  - name: product-service
    url: http://product-svc:8080
    routes:
      - name: product-routes
        paths:
          - /api/v1/products
        strip_path: false
    plugins:
      - name: jwt
      - name: rate-limiting
        config:
          minute: 100
          policy: redis
          redis_host: redis
      - name: cors
        config:
          origins: ["https://app.example.com"]
          methods: ["GET", "POST", "PUT", "DELETE"]

  - name: order-service
    url: http://order-svc:8080
    routes:
      - name: order-routes
        paths:
          - /api/v1/orders
    plugins:
      - name: jwt
      - name: rate-limiting
        config:
          minute: 50

3.2 關鍵插件

插件目的
jwt驗證 JWT 令牌
rate-limiting每個消費者的速率限制
corsCORS 標頭
request-transformer修改請求頭/內文
response-transformer修改回覆
prometheus指標端點
file-log / tcp-log記錄
ip-restriction白名單/黑名單 IP

4. APISIX 配置

routes:
  - uri: /api/v1/products/*
    upstream:
      type: roundrobin
      nodes:
        "product-svc:8080": 1
    plugins:
      jwt-auth:
        key: "product-key"
      limit-req:
        rate: 100
        burst: 50
        key_type: "var"
        key: "consumer_name"

  - uri: /api/v1/orders/*
    upstream:
      nodes:
        "order-svc:8080": 1
    plugins:
      jwt-auth: {}

5. 網關模式

5.1 基於路徑的路由

/api/v1/products/*  → Product Service
/api/v1/orders/*    → Order Service
/api/v1/users/*     → User Service
/api/v1/cart/*      → Cart Service

5.2 基於標頭的路由

X-API-Version: v2 → v2 service
X-Client-Type: mobile → mobile-optimized service

5.3 金絲雀路由

95% traffic → Product Service v1 (stable)
5% traffic  → Product Service v2 (canary)

6. API 閘道的 GitOps

Repository:
├── gateway/
│   ├── kong.yml (declarative config)
│   ├── plugins/
│   └── consumers/
└── .github/workflows/
    └── deploy-gateway.yml

CI/CD:
1. PR: change gateway config
2. Review: team review routing/auth changes
3. Merge: auto-apply via deck sync (Kong)
4. Monitor: check metrics after deploy

總結

  • API 閘道 = 所有 API 呼叫的單一入口點
  • 處理橫切:身份驗證、速率限制、路由、監控
  • Kong:通用、成熟、插件豐富
  • APISIX:透過 etcd 的高效能、動態插件
  • Envoy Gateway:K8s 網關 API 原生
  • GitOps:聲明式配置,版本控制

下一篇文章: 第 19 課:GraphQL Federation — 微前端的統一 API