api-gateway
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Gateway
API 网关
Gateway Pattern
网关模式
Client ──▶ API Gateway ──┬──▶ User Service
├──▶ Order Service
├──▶ Product Service
└──▶ Payment ServiceClient ──▶ API Gateway ──┬──▶ User Service
├──▶ Order Service
├──▶ Product Service
└──▶ Payment ServiceAWS API Gateway
AWS API Gateway
typescript
// CDK definition
const api = new apigateway.RestApi(this, 'MyApi', {
restApiName: 'My Service',
deployOptions: { stageName: 'prod', throttlingRateLimit: 1000, throttlingBurstLimit: 500 },
});
const orders = api.root.addResource('orders');
orders.addMethod('GET', new apigateway.LambdaIntegration(listOrdersFn));
orders.addMethod('POST', new apigateway.LambdaIntegration(createOrderFn), {
authorizer: cognitoAuthorizer,
authorizationType: apigateway.AuthorizationType.COGNITO,
});
// Usage plan with API key
const plan = api.addUsagePlan('BasicPlan', {
throttle: { rateLimit: 100, burstLimit: 50 },
quota: { limit: 10000, period: apigateway.Period.MONTH },
});typescript
// CDK definition
const api = new apigateway.RestApi(this, 'MyApi', {
restApiName: 'My Service',
deployOptions: { stageName: 'prod', throttlingRateLimit: 1000, throttlingBurstLimit: 500 },
});
const orders = api.root.addResource('orders');
orders.addMethod('GET', new apigateway.LambdaIntegration(listOrdersFn));
orders.addMethod('POST', new apigateway.LambdaIntegration(createOrderFn), {
authorizer: cognitoAuthorizer,
authorizationType: apigateway.AuthorizationType.COGNITO,
});
// Usage plan with API key
const plan = api.addUsagePlan('BasicPlan', {
throttle: { rateLimit: 100, burstLimit: 50 },
quota: { limit: 10000, period: apigateway.Period.MONTH },
});Kong (Declarative Config)
Kong(声明式配置)
yaml
undefinedyaml
undefinedkong.yml
kong.yml
_format_version: "3.0"
services:
-
name: user-service url: http://user-svc:3000 routes:
- name: users-route paths: ["/api/users"] strip_path: true plugins:
- name: rate-limiting config: { minute: 100, policy: redis, redis_host: redis }
- name: jwt
- name: cors config: origins: ["https://myapp.com"] methods: ["GET", "POST", "PUT", "DELETE"]
-
name: order-service url: http://order-svc:3000 routes:
- name: orders-route paths: ["/api/orders"] plugins:
- name: rate-limiting config: { minute: 50 }
undefined_format_version: "3.0"
services:
-
name: user-service url: http://user-svc:3000 routes:
- name: users-route paths: ["/api/users"] strip_path: true plugins:
- name: rate-limiting config: { minute: 100, policy: redis, redis_host: redis }
- name: jwt
- name: cors config: origins: ["https://myapp.com"] methods: ["GET", "POST", "PUT", "DELETE"]
-
name: order-service url: http://order-svc:3000 routes:
- name: orders-route paths: ["/api/orders"] plugins:
- name: rate-limiting config: { minute: 50 }
undefinedNGINX as Gateway
用 NGINX 作为网关
nginx
upstream user_service { server user-svc:3000; }
upstream order_service { server order-svc:3000; }
server {
listen 443 ssl;
location /api/users/ {
proxy_pass http://user_service/;
proxy_set_header X-Request-ID $request_id;
limit_req zone=api burst=20 nodelay;
}
location /api/orders/ {
proxy_pass http://order_service/;
proxy_set_header X-Request-ID $request_id;
}
}nginx
upstream user_service { server user-svc:3000; }
upstream order_service { server order-svc:3000; }
server {
listen 443 ssl;
location /api/users/ {
proxy_pass http://user_service/;
proxy_set_header X-Request-ID $request_id;
limit_req zone=api burst=20 nodelay;
}
location /api/orders/ {
proxy_pass http://order_service/;
proxy_set_header X-Request-ID $request_id;
}
}BFF (Backend for Frontend)
BFF(面向前端的后端)
typescript
// BFF aggregates multiple services for the frontend
app.get('/api/bff/dashboard', auth, async (req, res) => {
const [user, orders, notifications] = await Promise.all([
userService.getProfile(req.user.id),
orderService.getRecent(req.user.id, 5),
notificationService.getUnread(req.user.id),
]);
res.json({ user, recentOrders: orders, unreadCount: notifications.length });
});typescript
// BFF aggregates multiple services for the frontend
app.get('/api/bff/dashboard', auth, async (req, res) => {
const [user, orders, notifications] = await Promise.all([
userService.getProfile(req.user.id),
orderService.getRecent(req.user.id, 5),
notificationService.getUnread(req.user.id),
]);
res.json({ user, recentOrders: orders, unreadCount: notifications.length });
});Anti-Patterns
反模式
| Anti-Pattern | Fix |
|---|---|
| Business logic in gateway | Gateway only routes, auth, rate limits |
| No rate limiting | Configure per-route limits |
| Single point of failure | Deploy gateway with redundancy |
| No request ID propagation | Add X-Request-ID header for tracing |
| Gateway handles data transformation | Keep transformations in BFF or services |
| 反模式 | 解决方案 |
|---|---|
| 网关中包含业务逻辑 | 网关仅负责路由、认证、限流 |
| 未配置限流 | 按路由配置限流规则 |
| 存在单点故障 | 部署多实例网关保证冗余 |
| 未传递请求ID | 添加X-Request-ID头用于链路追踪 |
| 网关处理数据转换 | 数据转换逻辑放在BFF或业务服务中 |
Production Checklist
生产环境检查清单
- Rate limiting configured per route
- Authentication offloaded to gateway
- Request ID propagation for tracing
- Health check endpoints for upstream services
- Circuit breaker on upstream failures
- TLS termination at gateway
- 按路由配置限流规则
- 认证逻辑卸载到网关处理
- 配置请求ID传递用于链路追踪
- 上游服务配置健康检查端点
- 上游服务故障时启用熔断机制
- 网关侧完成TLS终止