name: api-gateway-configuration description: 配置API网关以进行路由、认证、限流和请求转换,适用于微服务架构。在设置Kong、Nginx、AWS API Gateway或Traefik以实现集中式API管理时使用。
API 网关配置
为微服务架构设计和配置API网关。
网关职责
- 请求路由和负载均衡
- 认证和授权
- 限流和节流
- 请求/响应转换
- 日志记录和监控
- SSL终止
Kong 配置 (YAML)
_format_version: "3.0"
services:
- name: user-service
url: http://user-service:3000
routes:
- name: user-routes
paths: ["/api/users"]
plugins:
- name: rate-limiting
config:
minute: 100
policy: local
- name: jwt
- name: order-service
url: http://order-service:3000
routes:
- name: order-routes
paths: ["/api/orders"]
Nginx 配置
upstream backend {
server backend1:3000 weight=5;
server backend2:3000 weight=5;
keepalive 32;
}
server {
listen 443 ssl;
location /api/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_cache_valid 200 1m;
}
location /health {
return 200 'OK';
}
}
AWS API Gateway (SAM)
Resources:
ApiGateway:
Type: AWS::Serverless::Api
Properties:
StageName: prod
Auth:
DefaultAuthorizer: JWTAuthorizer
Authorizers:
JWTAuthorizer:
JwtConfiguration:
issuer: !Sub "https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPoolId}"
最佳实践
- 在网关级别进行认证
- 实现全局限流
- 启用请求日志记录
- 使用后端健康检查
- 策略性地应用响应缓存
- 切勿在错误中暴露后端细节
- 在生产环境中强制执行HTTPS