关于 api-gateway-patterns
api-gateway-patterns 是一项围绕 Kong 设计和运营生产级 API 网关的技能,面向构建微服务网关的团队,涵盖路由、安全、流量控制与可观测性模式。
主要功能
- 01Kong 网关架构与实体
- 02路径、请求头、方法和主机路由
- 03速率限制与使用配额
- 04API 密钥、JWT、OAuth 2.0、OIDC 和 mTLS
- 05负载均衡与金丝雀流量模式
- 06日志、监控和 API 生命周期指南
适用场景
- 01在微服务间路由请求
- 02在网关实施身份验证和流量策略
- 03通过加权流量发布 API 版本
- 04规划网关安全与弹性
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ manutej/ luxor-claude-marketplace --skill api-gateway-patterns安装后在 Claude Code 中输入/api-gateway-patterns确认已加载。
附带文件EXAMPLES.mdREADME.md
详细介绍
API 网关模式
一套全面的技能,介绍如何使用 Kong 和行业最佳实践构建可用于生产环境的 API 网关。此技能涵盖微服务架构中的高级路由、身份验证、速率限制、负载均衡、流量管理和可观测性模式。
何时使用此技能
在以下情况下使用此技能:
- 为微服务架构实现 API 网关
- 管理流量路由、负载均衡和服务发现
- 在网关层实现身份验证和授权
- 实施速率限制、配额和流量策略
- 为 API 流量添加可观测性、日志记录和监控
- 实现请求/响应转换和缓存
- 管理 API 版本控制和弃用策略
- 设置断路器和弹性模式
- 配置多环境 API 部署
- 实施 API 安全策略(CORS、CSRF、WAF)
- 构建开发者门户和 API 文档
- 管理从开发到生产的 API 生命周期
核心概念
API 网关架构
API 网关充当客户端应用的单一入口点,将请求路由到相应的后端服务,同时处理横切关注点:
- 反向代理:将客户端请求路由到后端服务
- API 组合:聚合多个服务调用,并生成单个响应
- 协议转换:在不同协议之间转换(HTTP、gRPC、WebSocket)
- 横切关注点:身份验证、日志记录、速率限制、缓存
- 流量管理:负载均衡、断路、重试
- 安全性:SSL 终止、API 密钥验证、OAuth2 流程
网关的关键组件
- 服务:网关代理到的上游 API
- 路由:用于匹配请求并确定服务路由的规则
- 上游:服务实例的负载均衡器配置
- 插件:用于扩展功能的中间件(身份验证、日志记录等)
- 使用者:具有身份验证凭据的 API 客户端
- 证书:用于安全通信的 SSL/TLS 证书
- SNI:用于多域名 SSL 的服务器名称指示
Kong Gateway 基础知识
Kong 是一个云原生、平台无关、可扩展的 API 网关:
架构:
- 控制平面:用于配置管理的 Admin API
- 数据平面:处理运行时流量的代理层
- 数据库:用于存储配置的 PostgreSQL 或 Cassandra(也可采用无数据库模式)
- 插件系统:基于 Lua 的可扩展机制,用于实现自定义逻辑
核心实体:
Service (upstream API)
└── Routes (request matching)
└── Plugins (features/policies)
Upstream (load balancer)
└── Targets (service instances)
Consumer (API client)
└── Credentials (auth keys/tokens)
└── Plugins (consumer-specific policies)
路由模式
模式 1:基于路径的路由
根据 URL 路径将请求路由到不同的后端服务。
**使用场景:**具有不同 URL 前缀(如 /users、/orders、/products)的微服务
配置:
# Users Service
service:
name: users-service
url: http://users-api:8001
routes:
- name: users-route
paths:
- /users
- /api/users
strip_path: true
methods:
- GET
- POST
- PUT
- DELETE
# Orders Service
service:
name: orders-service
url: http://orders-api:8002
routes:
- name: orders-route
paths:
- /orders
- /api/orders
strip_path: true
关键选项:
strip_path: true- 代理前移除匹配的路径(例如,/users/123 → /123)strip_path: false- 保留完整路径(例如,/users/123 → /users/123)preserve_host: true- 将原始 Host 标头转发到上游
模式 2:基于标头的路由
根据 HTTP 标头进行路由,用于 A/B 测试、金丝雀部署或 API 版本控制。
**使用场景:**逐步推出新 API 版本或功能标志
配置:
# V1 Service (stable)
service:
name: api-v1
url: http://api-v1:8001
routes:
- name: api-v1-route
paths:
- /api
headers:
X-API-Version:
- "1"
- "1.0"
# V2 Service (beta)
service:
name: api-v2
url: http://api-v2:8002
routes:
- name: api-v2-route
paths:
- /api
headers:
X-API-Version:
- "2"
- "2.0"
# Default route (no version header)
routes:
- name: api-default
paths:
- /api
# Routes to V1 by default
高级标头路由:
# Mobile vs Web routing
routes:
- name: mobile-api
headers:
User-Agent:
- ".*Mobile.*"
- ".*Android.*"
- ".*iOS.*"
service: mobile-optimized-api
- name: web-api
headers:
User-Agent:
- ".*Chrome.*"
- ".*Firefox.*"
- ".*Safari.*"
service: web-api
模式 3:基于方法的路由
将不同的 HTTP 方法路由到专用服务。
**使用场景:**CQRS 模式——分离读服务和写服务
配置:
# Read Service (queries)
service:
name: query-service
url: http://read-api:8001
routes:
- name: read-operations
paths:
- /api/resources
methods:
- GET
- HEAD
- OPTIONS
# Write Service (commands)
service:
name: command-service
url: http://write-api:8002
routes:
- name: write-operations
paths:
- /api/resources
methods:
- POST
- PUT
- PATCH
- DELETE
模式 4:基于主机的路由
根据请求的主机名进行路由,适用于多租户应用。
**使用场景:**为不同客户或环境配置不同的子域名
配置:
# Tenant A
service:
name: tenant-a-api
url: http://tenant-a:8001
routes:
- name: tenant-a-route
hosts:
- tenant-a.api.example.com
- a.api.example.com
# Tenant B
service:
name: tenant-b-api
url: http://tenant-b:8002
routes:
- name: tenant-b-route
hosts:
- tenant-b.api.example.com
- b.api.example.com
# Wildcard for dynamic tenants
routes:
- name: dynamic-tenant
hosts:
- "*.api.example.com"
service: multi-tenant-api
模式 5:加权路由(金丝雀部署)
逐步将流量切换到不同版本的服务。
实现:
# Create two upstreams with weight distribution
upstream:
name: api-upstream
algorithm: round-robin
targets:
- target: api-v1:8001
weight: 90 # 90% traffic to stable version
- target: api-v2:8002
weight: 10 # 10% traffic to canary version
service:
name: api-service
host: api-upstream # Points to upstream
routes:
- name: api-route
paths:
- /api
渐进式发布策略:
- 开始:100% v1,0% v2
- 阶段 1:90% v1,10% v2(监控指标)
- 阶段 2:75% v1,25% v2
- 阶段 3:50% v1,50% v2
- 阶段 4:25% v1,75% v2
- 完成:0% v1,100% v2
限流模式
模式 1:全局限流
通过全局限额保护整个 API 免受滥用。
使用场景: 防止 DDoS 攻击并确保公平使用
配置:
plugins:
- name: rate-limiting
config:
minute: 1000
hour: 10000
day: 100000
policy: local # or 'cluster', 'redis'
fault_tolerant: true
hide_client_headers: false
limit_by: ip # or 'consumer', 'credential', 'service'
策略选项:
local:内存中存储,单节点(不支持集群)cluster:通过数据库在 Kong 节点间共享redis:通过 Redis 实现高性能分布式限流
模式 2:针对消费者的限流
为不同的 API 消费者(套餐等级)设置不同的限额。
使用场景: 采用分级定价的免费增值模式
配置:
# Free tier consumer
consumer:
username: free-user-123
plugins:
- name: rate-limiting
consumer: free-user-123
config:
minute: 10
hour: 100
day: 1000
# Premium tier consumer
consumer:
username: premium-user-456
plugins:
- name: rate-limiting
consumer: premium-user-456
config:
minute: 1000
hour: 10000
day: 100000
# Enterprise tier (unlimited)
consumer:
username: enterprise-user-789
# No rate limiting plugin for enterprise
模式 3:针对端点的限流
为不同的 API 端点设置不同的限额。
使用场景: 保护高开销操作,同时允许低开销操作使用更高的速率
配置:
# Expensive search endpoint - strict limits
routes:
- name: search-route
paths:
- /api/search
plugins:
- name: rate-limiting
route: search-route
config:
minute: 10
hour: 100
# Regular CRUD endpoints - moderate limits
routes:
- name: users-route
paths:
- /api/users
plugins:
- name: rate-limiting
route: users-route
config:
minute: 100
hour: 1000
# Health check - no limits
routes:
- name: health-route
paths:
- /health
# No rate limiting plugin
模式 4:滑动窗口限流
使用滑动窗口实现更精确的限流。
使用场景: 防止利用固定窗口边界的突发攻击
配置:
plugins:
- name: rate-limiting-advanced # Kong Enterprise
config:
limit:
- 100 # Limit value
window_size:
- 60 # Window in seconds
window_type: sliding
retry_after_jitter_max: 1
sync_rate: 0.5
namespace: my-api
strategy: redis
redis:
host: redis
port: 6379
database: 0
滑动窗口与固定窗口:
- 固定窗口:每分钟 100 个请求,在 :00 秒时重置
- 滑动窗口:任意 60 秒窗口内 100 个请求
- 滑动窗口可防止在窗口边界利用突发流量
模式 5:配额管理
长期使用配额(月度、年度)。
使用场景: 根据套餐强制执行订阅限额
配置:
plugins:
- name: request-termination
enabled: false # Will be enabled when quota exceeded
plugins:
- name: acme # Custom quota tracking plugin
config:
quota:
month: 1000000
reset_on: first_day
consumer_groups:
- name: starter
quota: 10000
- name: professional
quota: 100000
- name: enterprise
quota: 1000000
身份验证模式
模式 1:API 密钥身份验证
通过简单的 API 密钥验证实现基本安全防护。
使用场景: 内部 API、开发环境、简单集成
配置:
# Enable key-auth plugin
plugins:
- name: key-auth
config:
key_names:
- apikey
- api-key
- X-API-Key
hide_credentials: true
anonymous: null # Require authentication
run_on_preflight: false
# Create consumer with API key
consumers:
- username: mobile-app
custom_id: app-001
# Add key credential
keyauth_credentials:
- consumer: mobile-app
key: sk_live_abc123def456ghi789
用法:
curl -H "apikey: sk_live_abc123def456ghi789" \
https://api.example.com/users
最佳实践:
- 使用经过密码学安全随机生成的密钥(至少 32 个字符)
- 定期轮换密钥
- 为不同环境使用不同的密钥
- 切勿将密钥提交到版本控制系统
- 使用 HTTPS 保护传输中的密钥
模式 2:JWT 身份验证
通过验证载荷实现基于令牌的身份验证。
使用场景: 现代 SPA、移动应用、微服务
配置:
plugins:
- name: jwt
config:
uri_param_names:
- jwt
cookie_names:
- jwt_token
header_names:
- Authorization
claims_to_verify:
- exp
- nbf
key_claim_name: iss
secret_is_base64: false
anonymous: null
run_on_preflight: false
maximum_expiration: 3600 # 1 hour max
# Create consumer with JWT credential
consumers:
- username: web-app
jwt_secrets:
- consumer: web-app
key: myapp-issuer
algorithm: HS256
secret: my-secret-key-change-in-production
RS256(非对称)配置:
jwt_secrets:
- consumer: mobile-app
key: mobile-issuer
algorithm: RS256
rsa_public_key: |
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----
令牌格式:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJteWFwcC1pc3N1ZXIiLCJzdWIiOiJ1c2VyMTIzIiwiZXhwIjoxNjQwOTk1MjAwfQ.signature
模式 3:OAuth 2.0 授权
通过完整的 OAuth 2.0 流支持第三方集成。
使用场景: 公共 API、第三方开发者访问
支持的流程:
- 授权码流程
- 客户端凭据流程
- 隐式流程(已弃用)
- 资源所有者密码流程
配置:
plugins:
- name: oauth2
config:
scopes:
- read
- write
- admin
mandatory_scope: true
token_expiration: 3600
enable_authorization_code: true
enable_client_credentials: true
enable_implicit_grant: false
enable_password_grant: false
hide_credentials: true
accept_http_if_already_terminated: false
refresh_token_ttl: 1209600 # 14 days
# Create OAuth application
oauth2_credentials:
- consumer: third-party-app
name: "Partner Integration"
client_id: client_abc123
client_secret: secret_xyz789
redirect_uris:
- https://partner.com/callback
授权码流程:
# 1. Get authorization code
GET /oauth2/authorize?
response_type=code&
client_id=client_abc123&
redirect_uri=https://partner.com/callback&
scope=read write
# 2. Exchange code for token
POST /oauth2/token
grant_type=authorization_code&
client_id=client_abc123&
client_secret=secret_xyz789&
code=AUTH_CODE&
redirect_uri=https://partner.com/callback
模式 4:OpenID Connect(OIDC)
与身份提供商集成,实现企业级 SSO。
使用场景: 使用 Google、Okta、Auth0、Azure AD 进行企业身份验证
配置:
plugins:
- name: openid-connect
config:
issuer: https://accounts.google.com
client_id: your-client-id.apps.googleusercontent.com
client_secret: your-client-secret
redirect_uri:
- https://api.example.com/callback
scopes:
- openid
- email
- profile
auth_methods:
- authorization_code
login_redirect_uri: https://app.example.com/login
logout_redirect_uri: https://app.example.com/logout
ssl_verify: true
session_secret: change-this-secret-in-production
discovery: https://accounts.google.com/.well-known/openid-configuration
多提供商配置:
# Google OIDC
plugins:
- name: openid-connect
route: google-login
config:
issuer: https://accounts.google.com
client_id: google-client-id
client_secret: google-secret
# Azure AD OIDC
plugins:
- name: openid-connect
route: azure-login
config:
issuer: https://login.microsoftonline.com/tenant-id/v2.0
client_id: azure-client-id
client_secret: azure-secret
# Okta OIDC
plugins:
- name: openid-connect
route: okta-login
config:
issuer: https://dev-123456.okta.com
client_id: okta-client-id
client_secret: okta-secret
模式 5:mTLS(双向 TLS)身份验证
通过基于证书的身份验证保障服务间通信安全。
使用场景: 微服务双向身份验证、B2B 集成
配置:
# Enable mTLS plugin
plugins:
- name: mtls-auth
config:
ca_certificates:
- ca-cert-id-1
- ca-cert-id-2
skip_consumer_lookup: false
anonymous: null
revocation_check_mode: SKIP # or IGNORE_CA_ERROR, STRICT
# Upload CA certificate
ca_certificates:
- cert: |
-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAKL...
-----END CERTIFICATE-----
# Create consumer mapped to client certificate
consumers:
- username: service-a
custom_id: service-a-001
# Map certificate to consumer
mtls_auth_credentials:
- consumer: service-a
subject_name: CN=service-a,O=MyOrg
负载均衡模式
模式 1:轮询负载均衡
在各服务实例间均匀分配请求。
使用场景: 容量相同的无状态服务
配置:
upstreams:
- name: api-upstream
algorithm: round-robin
slots: 10000
healthchecks:
active:
type: http
http_path: /health
healthy:
interval: 5
successes: 2
unhealthy:
interval: 5
http_failures: 3
timeouts: 3
passive:
healthy:
successes: 5
unhealthy:
http_failures: 5
timeouts: 2
targets:
- upstream: api-upstream
target: api-1.internal:8001
weight: 100
- upstream: api-upstream
target: api-2.internal:8001
weight: 100
- upstream: api-upstream
target: api-3.internal:8001
weight: 100
模式 2:加权负载均衡
根据服务器容量按比例分配流量。
使用场景: 容量不同的异构服务器
配置:
upstreams:
- name: api-upstream
algorithm: round-robin
targets:
# Powerful server - 50% traffic
- target: api-1.internal:8001
weight: 500
# Medium server - 30% traffic
- target: api-2.internal:8001
weight: 300
# Small server - 20% traffic
- target: api-3.internal:8001
weight: 200
权重分配:
- 总权重:500 + 300 + 200 = 1000
- api-1:500/1000 = 50% 的请求
- api-2:300/1000 = 30% 的请求
- api-3:200/1000 = 20% 的请求
模式 3:一致性哈希
将来自同一客户端的请求路由到同一后端(会话亲和性)。
使用场景: 需要会话持久性的有状态服务
配置:
upstreams:
- name: api-upstream
algorithm: consistent-hashing
hash_on: header
hash_on_header: X-User-ID
hash_fallback: ip
hash_fallback_header: X-Forwarded-For
targets:
- target: api-1.internal:8001
- target: api-2.internal:8001
- target: api-3.internal:8001
哈希选项:
hash_on: none- 随机分配hash_on: consumer- 按经过身份验证的使用者进行哈希hash_on: ip- 按客户端 IP 进行哈希hash_on: header- 按指定的标头值进行哈希hash_on: cookie- 按 Cookie 值进行哈希hash_on: path- 按请求路径进行哈希
不同哈希类型的使用场景:
- 用户会话:
hash_on: header(X-User-ID) - 地理位置路由:
hash_on: ip - 租户隔离:
hash_on: header(X-Tenant-ID) - 购物车:
hash_on: cookie(session_id)
模式 4:最少连接数
路由到活动连接数最少的服务器。
使用场景: 长连接(WebSockets、流式传输)
配置:
upstreams:
- name: websocket-upstream
algorithm: least-connections
targets:
- target: ws-1.internal:8001
- target: ws-2.internal:8001
- target: ws-3.internal:8001
适用场景:
- WebSocket 服务器
- 长轮询端点
- 流式 API(SSE、gRPC 流式传输)
- 请求持续时间不一的服务
模式 5:主动健康检查
自动将不健康的目标从轮询中移除。
使用场景: 实现自动故障转移的高可用性
配置:
upstreams:
- name: api-upstream
healthchecks:
active:
type: http
http_path: /health
https_verify_certificate: true
concurrency: 10
timeout: 1
headers:
X-Health-Check:
- gateway
healthy:
interval: 5 # Check every 5 seconds
http_statuses:
- 200
- 302
successes: 2 # 2 successes → healthy
unhealthy:
interval: 5
http_statuses:
- 429
- 500
- 503
http_failures: 3 # 3 failures → unhealthy
tcp_failures: 3
timeouts: 3
passive:
type: http
healthy:
http_statuses:
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 226
- 300
- 301
- 302
successes: 5
unhealthy:
http_statuses:
- 429
- 500
- 503
http_failures: 5
tcp_failures: 2
timeouts: 2
流量控制模式
模式 1:熔断器
下游服务不健康时快速失败,防止故障级联。
使用场景: 依赖项发生故障时保护系统
配置:
plugins:
- name: proxy-cache-advanced # Kong Enterprise
config:
# Serve stale cache during outages
cache_control: false
plugins:
- name: request-termination
enabled: false # Enabled programmatically on circuit open
# Custom circuit breaker (via passive health checks)
upstreams:
- name: api-upstream
healthchecks:
passive:
unhealthy:
http_failures: 5 # Open circuit after 5 failures
timeouts: 3
healthy:
successes: 3 # Close circuit after 3 successes
熔断器状态:
- 关闭:正常运行,请求正常通过
- 打开:检测到故障,请求立即失败
- 半开:测试服务是否已恢复,仅允许有限数量的请求通过
模式 2:请求超时
防止缓慢的请求长时间占用资源。
使用场景: 防止缓慢的后端导致资源耗尽
配置:
services:
- name: api-service
url: http://api.internal:8001
read_timeout: 5000 # 5 seconds
write_timeout: 5000 # 5 seconds
connect_timeout: 2000 # 2 seconds
plugins:
- name: request-timeout # Additional timeout enforcement
config:
http_timeout: 5000
stream_timeout: 30000
超时策略:
connect_timeout: 2s → Connection establishment
write_timeout: 5s → Writing request to upstream
read_timeout: 5s → Reading response from upstream
http_timeout: 5s → Overall HTTP transaction
模式 3:重试逻辑
使用指数退避策略自动重试失败的请求。
使用场景: 处理分布式系统中的瞬时故障
配置:
services:
- name: api-service
retries: 5 # Maximum retry attempts
plugins:
- name: proxy-retry # Custom retry plugin
config:
retries: 3
retry_on:
- 500
- 502
- 503
- 504
backoff:
type: exponential
base: 2
max: 30
jitter: 0.5
重试计划:
Attempt 1: Immediate
Attempt 2: 2s + jitter
Attempt 3: 4s + jitter
Attempt 4: 8s + jitter
Attempt 5: 16s + jitter
幂等性注意事项:
- 重试 GET、HEAD、PUT、DELETE(幂等请求)
- 除非使用幂等性密钥,否则不要重试 POST
- 检查 Idempotency-Key 标头
模式 4:请求大小限制
防止大负载攻击和内存耗尽。
使用场景: 防止请求正文过大
配置:
plugins:
- name: request-size-limiting
config:
allowed_payload_size: 10 # Megabytes
size_unit: megabytes
require_content_length: true
# Different limits per route
plugins:
- name: request-size-limiting
route: file-upload
config:
allowed_payload_size: 100 # Allow larger files
- name: request-size-limiting
route: api-endpoints
config:
allowed_payload_size: 1 # Strict limit for APIs
模式 5:流量整形(节流)
控制请求速率,提供比简单速率限制更精细的控制。
使用场景: 平滑流量峰值,防止后端过载
配置:
plugins:
- name: request-transformer-advanced
config:
# Add delay headers for client-side throttling
add:
headers:
- "Retry-After:60"
plugins:
- name: proxy-cache-advanced
config:
# Cache responses to reduce backend load
cache_ttl: 300
strategy: memory
# Upstream connection limits
upstreams:
- name: api-upstream
slots: 1000 # Limit concurrent connections
请求/响应转换
模式 1:请求标头操作
代理转发前添加、修改或移除请求标头。
使用场景: 添加身份验证、跟踪或上下文标头
配置:
plugins:
- name: request-transformer
config:
add:
headers:
- "X-Gateway:kong"
- "X-Request-ID:$(uuid)"
- "X-Forwarded-Proto:https"
append:
headers:
- "X-Trace-Id:$(uuid)"
replace:
headers:
- "User-Agent:Kong-Gateway/3.0"
remove:
headers:
- "X-Internal-Secret"
高级转换:
plugins:
- name: request-transformer-advanced
config:
add:
headers:
- "X-Consumer-Username:$(consumer_username)"
- "X-Consumer-ID:$(consumer_id)"
- "X-Authenticated-Scope:$(authenticated_credential.scope)"
- "X-Client-IP:$(remote_addr)"
rename:
headers:
- "Authorization:X-Original-Auth"
模式 2:响应标头操作
返回给客户端前修改响应标头。
使用场景: 添加安全标头、CORS、缓存指令
配置:
plugins:
- name: response-transformer
config:
add:
headers:
- "X-Gateway-Response-Time:$(latencies.request)"
- "X-Server-ID:$(upstream_addr)"
remove:
headers:
- "X-Powered-By"
- "Server"
# Security headers
plugins:
- name: response-transformer
config:
add:
headers:
- "Strict-Transport-Security:max-age=31536000; includeSubDomains"
- "X-Content-Type-Options:nosniff"
- "X-Frame-Options:DENY"
- "X-XSS-Protection:1; mode=block"
- "Content-Security-Policy:default-src 'self'"
模式 3:请求正文转换
转发前修改请求负载。
使用场景: 添加字段、转换格式、清理输入
配置:
plugins:
- name: request-transformer-advanced
config:
add:
body:
- "gateway_timestamp:$(timestamp)"
- "request_id:$(uuid)"
remove:
body:
- "internal_field"
replace:
body:
- "api_version:v2"
模式 4:GraphQL 到 REST 的转换
将 REST API 作为 GraphQL 端点开放。
使用场景: 使用 GraphQL 改造旧版 REST API
配置:
plugins:
- name: graphql-proxy-cache-advanced
config:
strategy: memory
# Define GraphQL schema mapping
graphql_schemas:
- name: users-graphql
schema: |
type Query {
user(id: ID!): User
users: [User]
}
type User {
id: ID!
name: String!
email: String!
}
resolvers:
Query:
user: http://users-api/users/{id}
users: http://users-api/users
模式 5:协议转换
在 HTTP、gRPC 和 WebSocket 协议之间进行转换。
使用场景: 通过 HTTP/JSON 开放 gRPC 服务
配置:
# gRPC to HTTP/JSON
plugins:
- name: grpc-gateway
config:
proto: /path/to/service.proto
services:
- name: grpc-service
url: grpc://grpc.internal:9000
protocol: grpc
routes:
- name: grpc-http-route
paths:
- /v1/users
protocols:
- http
- https
缓存模式
模式 1:响应缓存
缓存上游响应以减轻后端负载。
使用场景: 缓存开销较大的查询,减轻数据库负载
配置:
plugins:
- name: proxy-cache
config:
strategy: memory # or 'redis'
content_type:
- "application/json"
- "text/html"
cache_ttl: 300 # 5 minutes
cache_control: false # Ignore client cache headers
storage_ttl: 600 # Backend storage TTL
memory:
dictionary_name: kong_cache
vary_headers:
- "Accept-Language"
- "X-User-Tier"
基于 Redis 的缓存:
plugins:
- name: proxy-cache-advanced
config:
strategy: redis
cache_ttl: 3600
redis:
host: redis.internal
port: 6379
database: 0
password: redis-password
timeout: 2000
sentinel_master: mymaster
sentinel_addresses:
- redis-sentinel-1:26379
- redis-sentinel-2:26379
模式 2:条件缓存
根据状态码、标头或请求条件进行缓存。
使用场景: 仅缓存成功响应,跳过错误响应
配置:
plugins:
- name: proxy-cache-advanced
config:
response_code:
- 200
- 301
- 302
request_method:
- GET
- HEAD
vary_headers:
- "Accept"
- "Accept-Encoding"
vary_query_params:
- "page"
- "limit"
ignore_uri_case: true
模式 3:缓存失效
按需或根据事件清除缓存。
使用场景: 数据变更时更新缓存
配置:
# Admin API cache purge
POST /cache/purge
# Purge specific endpoint
POST /cache/purge/users
# TTL-based expiration
plugins:
- name: proxy-cache
config:
cache_ttl: 60 # Short TTL for frequently updated data
# Event-based invalidation (custom plugin)
plugins:
- name: custom-cache-invalidator
config:
invalidate_on:
- POST
- PUT
- PATCH
- DELETE
propagate: true # Clear related caches
模式 4:多层缓存
在网关和后端分层缓存。
使用场景: 最大限度提高各层的缓存命中率
架构:
Client
↓
Kong Gateway Cache (L1)
↓
Backend API Cache (L2)
↓
Database
配置:
# Gateway cache (L1)
plugins:
- name: proxy-cache
config:
strategy: memory
cache_ttl: 60 # 1 minute
# Backend passes Cache-Control headers
# Gateway respects them if cache_control: true
plugins:
- name: proxy-cache
config:
cache_control: true # Respect upstream Cache-Control
vary_headers:
- "Cache-Control"
模式 5:基于 Surrogate-Key 的失效
为缓存添加标签,以便进行精细化失效。
使用场景: 高效地使相关资源失效
配置:
# Tag responses with surrogate keys
plugins:
- name: response-transformer
config:
add:
headers:
- "Surrogate-Key:user-$(user_id) tenant-$(tenant_id)"
# Invalidate by surrogate key
# Custom plugin or Varnish integration
POST /cache/purge
Headers:
Surrogate-Key: user-123
安全模式
模式 1:CORS(跨源资源共享)
启用受控的跨源请求。
使用场景: Web 应用从不同域调用 API
配置:
plugins:
- name: cors
config:
origins:
- "https://app.example.com"
- "https://admin.example.com"
methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
headers:
- Accept
- Authorization
- Content-Type
- X-Request-ID
exposed_headers:
- X-Total-Count
- X-Page-Number
credentials: true
max_age: 3600
preflight_continue: false
通配符 CORS(仅限开发环境):
plugins:
- name: cors
config:
origins:
- "*"
methods:
- "*"
headers:
- "*"
credentials: false # Must be false with wildcard origins
模式 2:IP 限制
根据 IP 地址允许或拒绝访问。
使用场景: 将管理 API 限制为仅办公 IP 可访问
配置:
# Whitelist approach
plugins:
- name: ip-restriction
config:
allow:
- 10.0.0.0/8
- 192.168.1.100
- 203.0.113.0/24
# Blacklist approach
plugins:
- name: ip-restriction
config:
deny:
- 1.2.3.4
- 5.6.7.0/24
与身份验证结合:
# Admin route: IP + Auth
plugins:
- name: ip-restriction
route: admin-api
config:
allow:
- 10.0.0.0/8
- name: key-auth
route: admin-api
模式 3:机器人检测
检测并阻止恶意机器人。
使用场景: 防止抓取、暴力破解和垃圾信息
配置:
plugins:
- name: bot-detection
config:
allow:
- "googlebot"
- "bingbot"
- "slackbot"
deny:
- "curl"
- "wget"
- "scrapy"
blacklist_cache_size: 10000
whitelist_cache_size: 10000
模式 4:请求验证
根据架构验证请求。
使用场景: 确保符合 API 契约,防止注入
配置:
plugins:
- name: request-validator
config:
body_schema: |
{
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 3,
"maxLength": 50
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 18,
"maximum": 120
}
},
"required": ["username", "email"]
}
parameter_schema:
- name: page
in: query
required: false
schema:
type: integer
minimum: 1
模式 5:WAF(Web 应用防火墙)
防范 OWASP Top 10 漏洞。
使用场景: 阻止 SQL 注入、XSS、路径遍历
配置:
plugins:
- name: waf # Kong Enterprise or ModSecurity plugin
config:
rule_sets:
- owasp_crs
anomaly_threshold: 5
paranoia_level: 1
blocked_status_code: 403
可观测性模式
模式 1:请求日志记录
记录所有 API 请求,用于审计和调试。
使用场景: 合规、调试、分析
配置:
plugins:
- name: file-log
config:
path: /var/log/kong/requests.log
reopen: true
# JSON structured logging
plugins:
- name: http-log
config:
http_endpoint: http://logstash:5000
method: POST
content_type: application/json
timeout: 5000
keepalive: 60000
custom_fields_by_lua:
request_id: "return kong.request.get_header('X-Request-ID')"
记录到多个目标:
# Elasticsearch
plugins:
- name: http-log
config:
http_endpoint: http://elasticsearch:9200/_bulk
# Splunk
plugins:
- name: http-log
config:
http_endpoint: https://splunk:8088/services/collector
headers:
Authorization: "Splunk token"
# Datadog
plugins:
- name: datadog
config:
host: datadog-agent
port: 8125
模式 2:分布式追踪
跟踪跨微服务的请求。
使用场景: 诊断延迟,了解请求流向
配置:
# Zipkin
plugins:
- name: zipkin
config:
http_endpoint: http://zipkin:9411/api/v2/spans
sample_ratio: 0.1 # Trace 10% of requests
include_credential: true
traceid_byte_count: 16
header_type: preserve # or 'jaeger', 'b3', 'w3c'
# Jaeger
plugins:
- name: opentelemetry
config:
endpoint: http://jaeger:14268/api/traces
resource_attributes:
service.name: api-gateway
service.version: 1.0.0
batch_span_processor:
max_queue_size: 2048
batch_timeout: 5000
W3C Trace Context:
plugins:
- name: opentelemetry
config:
propagation:
default: w3c
headers:
- traceparent
- tracestate
模式 3:指标收集
公开 Prometheus 指标以供监控。
使用场景: 监控网关性能、错误和延迟
配置:
plugins:
- name: prometheus
config:
per_consumer: true
status_code_metrics: true
latency_metrics: true
bandwidth_metrics: true
upstream_health_metrics: true
# Expose /metrics endpoint
routes:
- name: metrics
paths:
- /metrics
service: prometheus-service
可用指标:
# Requests
kong_http_requests_total{service,route,code}
# Latency
kong_latency_ms{type,service,route}
kong_request_latency_ms{service,route}
kong_upstream_latency_ms{service,route}
# Bandwidth
kong_bandwidth_bytes{type,service,route}
# Connections
kong_datastore_reachable
kong_nginx_connections_total{state}
模式 4:运行状况检查
公开运行状况检查端点。
使用场景: Kubernetes 存活/就绪探针
配置:
# Gateway health
routes:
- name: health
paths:
- /health
plugins:
- name: request-termination
config:
status_code: 200
message: "OK"
# Detailed status
routes:
- name: status
paths:
- /status
service: kong-status-service
# Upstream health aggregation
plugins:
- name: upstream-health-check
config:
healthy_threshold: 2
unhealthy_threshold: 3
模式 5:错误跟踪
跟踪错误并将其报告给监控系统。
使用场景: 主动检测错误并发出警报
配置:
# Sentry integration
plugins:
- name: sentry
config:
dsn: https://[email protected]/project
environment: production
release: v1.2.3
# Custom error logging
plugins:
- name: http-log
config:
http_endpoint: http://error-tracker:5000
custom_fields_by_lua:
error_type: |
if kong.response.get_status() >= 500 then
return "server_error"
elseif kong.response.get_status() >= 400 then
return "client_error"
end
多环境模式
模式 1:环境隔离
为开发、预发布和生产环境分别配置。
使用场景: 确保在各环境中一致部署
结构:
config/
├── base.yaml # Shared configuration
├── dev.yaml # Development overrides
├── staging.yaml # Staging overrides
└── production.yaml # Production overrides
配置:
# base.yaml
_format_version: "3.0"
services:
- name: users-api
url: http://users-service:8001
routes:
- name: users-route
service: users-api
paths:
- /users
# production.yaml
_format_version: "3.0"
services:
- name: users-api
url: https://users-api-prod.internal:8001
retries: 5
read_timeout: 5000
plugins:
- name: rate-limiting
service: users-api
config:
minute: 1000
模式 2:蓝绿部署
实现零停机部署并可即时回滚。
使用场景: 安全地部署到生产环境
配置:
# Blue environment (current production)
upstreams:
- name: api-blue
targets:
- target: api-blue-1:8001
- target: api-blue-2:8001
# Green environment (new version)
upstreams:
- name: api-green
targets:
- target: api-green-1:8001
- target: api-green-2:8001
# Route points to active environment
services:
- name: api-service
host: api-blue # Switch to api-green for deployment
# Rollback: Switch service.host back to api-blue
模式 3:金丝雀发布
通过监控逐步推出。
使用场景: 降低新版本发布的风险
配置:
# Canary routing with header
routes:
- name: api-canary
paths:
- /api
headers:
X-Canary:
- "true"
service: api-v2
routes:
- name: api-stable
paths:
- /api
service: api-v1
# Weighted canary (10% traffic)
upstreams:
- name: api-upstream
targets:
- target: api-v1:8001
weight: 90
- target: api-v2:8001
weight: 10
金丝雀发布进度:
Phase 1: 5% canary, monitor errors
Phase 2: 25% canary, check metrics
Phase 3: 50% canary, verify performance
Phase 4: 100% canary, deprecate old version
模式 4:功能标志
动态启用或禁用功能。
使用场景: A/B 测试、逐步推出功能
配置:
# Feature flag via header
routes:
- name: new-feature
paths:
- /api/new-feature
headers:
X-Feature-Flag:
- "new-dashboard"
service: new-feature-service
# Default route (feature disabled)
routes:
- name: old-feature
paths:
- /api/new-feature
service: old-feature-service
# Consumer-based feature flags
plugins:
- name: request-transformer
consumer: beta-users
config:
add:
headers:
- "X-Feature-Flags:new-dashboard,advanced-search"
模式 5:多区域部署
将请求路由到最近的区域,以降低延迟。
使用场景: 支持区域故障转移的全球 API
配置:
# US region
upstreams:
- name: api-us
targets:
- target: api-us-east:8001
- target: api-us-west:8001
# EU region
upstreams:
- name: api-eu
targets:
- target: api-eu-west:8001
- target: api-eu-central:8001
# Geographic routing (via DNS or header)
routes:
- name: us-traffic
hosts:
- us.api.example.com
service: api-us-service
routes:
- name: eu-traffic
hosts:
- eu.api.example.com
service: api-eu-service
最佳实践
架构设计
- 单一职责:网关仅处理横切关注点
- 无状态设计:保持网关无状态,以便水平扩展
- 声明式配置:使用 YAML/JSON 管理配置,并进行版本控制
- 无数据库模式:使用无数据库模式简化部署
- 精简插件:仅启用必要的插件
安全最佳实践
- 纵深防御:叠加多种安全机制
- 最小权限:为使用者配置最少权限
- 机密管理:切勿将凭据硬编码
- 全程使用 TLS:加密所有流量(客户端和上游)
- 速率限制:始终保护公开端点
- 输入验证:验证所有请求数据
- 定期更新:及时更新 Kong 和插件
性能优化
- 启用缓存:尽可能积极地缓存响应
- 连接池:重复使用上游连接
- 负载均衡:均匀分配负载
- 健康检查:快速移除不健康的目标
- 超时:设置适当的超时时间,避免挂起
- 监控:跟踪延迟、错误和吞吐量
- 资源限制:设置内存和连接限制
卓越运营
- 日志记录:为所有请求记录结构化日志
- 监控:全面收集指标
- 告警:针对异常和错误发出告警
- 文档:记录所有路由和插件
- 测试:在预发布环境中测试网关配置
- 版本管理:对所有配置进行版本控制
- 灾难恢复:规划故障转移方案
插件策略
- 顺序很重要:插件按特定顺序执行
- 合理确定作用范围:全局、服务、路由或使用者
- 全面测试:测试插件组合
- 监控影响:跟踪插件带来的性能开销
- 自定义插件:针对独特需求编写自定义插件
插件执行顺序:
1. Authentication (key-auth, jwt, oauth2)
2. Security (ip-restriction, bot-detection)
3. Traffic Control (rate-limiting, request-size-limiting)
4. Transformation (request-transformer)
5. Logging (file-log, http-log)
6. Analytics (prometheus, datadog)
配置管理
- 版本控制:使用 Git 管理所有配置
- 环境一致性:确保不同环境的配置保持一致
- 自动化部署:通过 CI/CD 管理配置变更
- 验证:应用配置前先进行验证
- 回滚计划:出现问题时快速回滚
- 变更日志:记录所有配置变更
扩展指南
- 水平扩展:增加更多 Kong 节点
- 数据库扩展:单独扩展 PostgreSQL
- 缓存卸载:使用 Redis 进行分布式缓存
- 区域部署:在靠近用户的位置部署
- CDN 集成:卸载静态内容
- 连接限制:设置每个工作进程的连接限制
常见用例
用例 1:SaaS API 平台
需求:
- 多租户隔离
- 分级定价(免费、专业版、企业版)
- 按层级进行速率限制
- 按客户进行分析
- 自助式开发者门户
实现:
# Tenant identification
plugins:
- name: key-auth
config:
key_names:
- X-API-Key
# Tier-based rate limiting
consumers:
- username: free-tier-customer
custom_id: customer-123
plugins:
- name: rate-limiting
consumer: free-tier-customer
config:
minute: 60
hour: 1000
# Usage analytics
plugins:
- name: prometheus
config:
per_consumer: true
# Request transformation (add tenant context)
plugins:
- name: request-transformer
config:
add:
headers:
- "X-Tenant-ID:$(consumer_custom_id)"
用例 2:微服务网关
需求:
- 服务发现
- 负载均衡
- 熔断
- 分布式追踪
- 集中式身份验证
实现:
# Service registry
services:
- name: users-service
url: http://users.internal:8001
- name: orders-service
url: http://orders.internal:8002
- name: inventory-service
url: http://inventory.internal:8003
# Load balancing with health checks
upstreams:
- name: users-upstream
healthchecks:
active:
http_path: /health
healthy:
interval: 5
# Distributed tracing
plugins:
- name: zipkin
config:
http_endpoint: http://zipkin:9411/api/v2/spans
# JWT authentication (single sign-on)
plugins:
- name: jwt
config:
claims_to_verify:
- exp
用例 3:移动后端
需求:
- 有版本管理的 API
- GraphQL 支持
- 离线缓存
- 推送通知
- 基于设备的速率限制
实现:
# API versioning
routes:
- name: api-v1
paths:
- /api/v1
service: mobile-api-v1
- name: api-v2
paths:
- /api/v2
service: mobile-api-v2
# GraphQL endpoint
plugins:
- name: graphql-proxy-cache-advanced
route: graphql-route
# Aggressive caching for mobile
plugins:
- name: proxy-cache
config:
cache_ttl: 3600
strategy: redis
# Device-based rate limiting
plugins:
- name: rate-limiting
config:
limit_by: header
header_name: X-Device-ID
minute: 100
用例 4:公共 API
需求:
- OAuth 2.0
- 开发者门户
- API 文档
- 使用情况分析
- 变现
实现:
# OAuth 2.0
plugins:
- name: oauth2
config:
scopes:
- read
- write
- admin
enable_authorization_code: true
# Developer portal
routes:
- name: developer-docs
paths:
- /docs
service: developer-portal
# Usage tracking
plugins:
- name: prometheus
config:
per_consumer: true
# Billing integration
plugins:
- name: http-log
config:
http_endpoint: http://billing-system:5000
用例 5:旧系统现代化
需求:
- REST 转 GraphQL
- 协议转换
- 请求/响应转换
- 渐进式迁移
- 向后兼容
实现:
# GraphQL facade over REST
plugins:
- name: graphql-proxy-cache-advanced
# SOAP to REST transformation
plugins:
- name: request-transformer-advanced
config:
# Transform REST to SOAP
replace:
headers:
- "Content-Type:text/xml"
# Version migration (route legacy to new)
upstreams:
- name: api-upstream
targets:
- target: legacy-api:8001
weight: 20 # 20% legacy
- target: new-api:8002
weight: 80 # 80% new
快速参考
基本命令
# Declarative configuration
deck sync -s kong.yaml
# Database migrations
kong migrations bootstrap
kong migrations up
# Start Kong
kong start
# Reload configuration
kong reload
# Health check
curl http://localhost:8001/status
# List services
curl http://localhost:8001/services
# List routes
curl http://localhost:8001/routes
# List plugins
curl http://localhost:8001/plugins
配置模板
最简服务:
services:
- name: my-service
url: http://api.internal:8001
routes:
- name: my-route
service: my-service
paths:
- /api
生产服务:
services:
- name: production-service
url: http://api.internal:8001
protocol: http
retries: 5
connect_timeout: 5000
read_timeout: 60000
write_timeout: 60000
upstreams:
- name: production-upstream
algorithm: consistent-hashing
hash_on: header
hash_on_header: X-User-ID
healthchecks:
active:
http_path: /health
healthy:
interval: 5
successes: 2
unhealthy:
http_failures: 3
timeouts: 3
targets:
- upstream: production-upstream
target: api-1:8001
- upstream: production-upstream
target: api-2:8001
routes:
- name: production-route
service: production-service
paths:
- /api
protocols:
- https
strip_path: true
preserve_host: false
plugins:
- name: rate-limiting
route: production-route
config:
minute: 1000
policy: redis
- name: jwt
route: production-route
- name: cors
route: production-route
- name: prometheus
route: production-route
资源
- Kong 文档:https://docs.konghq.com/
- Kong Gateway:https://konghq.com/kong/
- Kong 插件中心:https://docs.konghq.com/hub/
- Kong Admin API:https://docs.konghq.com/gateway/latest/admin-api/
- decK(声明式配置):https://docs.konghq.com/deck/
- Kong Ingress Controller:https://docs.konghq.com/kubernetes-ingress-controller/
- Kong 社区:https://discuss.konghq.com/
技能版本:1.0.0 最后更新:2025 年 10 月 技能类别:API 网关、微服务、流量管理 兼容对象:Kong Gateway 3.x、Kubernetes、Docker、云平台