关于 api-gateway
api-gateway 是供开发者设计 API 网关架构的参考技能,包含 AWS API Gateway、Kong、NGINX 和 BFF 模式示例,以及运维检查项。
主要功能
- 01网关路由模式
- 02AWS API Gateway 示例
- 03Kong 声明式配置
- 04NGINX 网关配置
- 05BFF 聚合模式
- 06生产就绪检查清单
适用场景
- 01将请求路由到后端服务
- 02配置网关速率限制
- 03为前端聚合多个服务的数据
- 04检查网关部署准备情况
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill api-gateway安装后在 Claude Code 中输入/api-gateway确认已加载。
详细介绍
API 网关
网关模式
Client ──▶ API Gateway ──┬──▶ User Service
├──▶ Order Service
├──▶ Product Service
└──▶ Payment Service
AWS API Gateway
// 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(声明式配置)
# 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 }
将 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(面向前端的后端)
// 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 });
});
反模式
| 反模式 | 修复方法 |
|---|---|
| 在网关中编写业务逻辑 | 网关仅负责路由、身份验证和速率限制 |
| 未设置速率限制 | 为每个路由配置限制 |
| 单点故障 | 部署冗余网关 |
| 未传递请求 ID | 添加 X-Request-ID 标头以进行跟踪 |
| 网关处理数据转换 | 将转换逻辑保留在 BFF 或服务中 |
生产环境检查清单
- 为每个路由配置速率限制
- 将身份验证卸载到网关
- 传递请求 ID 以进行跟踪
- 为上游服务提供健康检查端点
- 在上游服务故障时启用断路器
- 在网关处终止 TLS
评论
支持 Markdown