🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
康养机器人 API 网关
基于 Kong Gateway 的高性能、安全的 API 网关解决方案,为康养机器人平台提供统一的服务入口。
🏗️ 架构概览
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────────┐
│ │ │ │ │ │
│ 客户端应用 │────│ Nginx + SSL │────│ Kong Gateway │
│ │ │ │ │ │
└─────────────────┘ └──────────────────┘ └─────────────────────────┘
│
┌──────────────────┐ │
│ │ │
│ JWT 认证服务 │────────────────┘
│ │
└──────────────────┘
│
┌─────────────────────────────────────────────────────────────────────────┐
│ 微服务集群 │
├─────────────────────────────────────────────────────────────────────────┤
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ │ │ │ │ │ │
│ │ 健康监测服务 │ │ 陪伴服务 │ │ 康复训练服务 │ │
│ │ │ │ │ │ │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
🚀 快速开始
前置要求
- Docker 20.10+
- Docker Compose 2.0+
- 8000-8080 端口可用
一键部署
# 克隆项目
git clone <repository>
cd robot/api-gateway
# 执行部署脚本
./deploy.sh
手动部署
# 1. 创建Docker网络
docker network create kangyang-network
# 2. 生成SSL证书
mkdir -p ssl
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout ssl/api.kangyang-robot.com.key \
-out ssl/api.kangyang-robot.com.crt \
-subj "/C=CN/ST=Beijing/L=Beijing/O=KangYang/CN=api.kangyang-robot.com"
# 3. 启动服务
docker-compose up -d
# 4. 应用Kong配置
curl -X POST http://localhost:8001/config -F config=@kong.yml
📡 服务端点
| 服务 | 端口 | 协议 | 描述 |
|---|---|---|---|
| Kong Proxy | 8000 | HTTP/HTTPS | 主要API网关入口 |
| Kong Admin | 8001 | HTTP | Kong管理API |
| Konga UI | 1337 | HTTP | Kong可视化管理界面 |
| JWT Service | 8080 | HTTP | JWT认证服务 |
| Nginx Status | 8080 | HTTP | Nginx状态监控 |
🔐 认证系统
JWT Token 获取
# 获取管理员Token
curl -X POST http://localhost:8080/api/v1/auth/token \
-H 'Content-Type: application/json' \
-d '{
"username": "admin",
"user_type": "admin",
"user_id": "admin001"
}'
# 响应示例
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_at": "2024-01-02T10:00:00Z",
"user_type": "admin"
}
Token 验证
# 验证Token有效性
curl -X POST http://localhost:8080/api/v1/auth/validate \
-H 'Authorization: Bearer YOUR_TOKEN'
Token 刷新
# 刷新Token
curl -X POST http://localhost:8080/api/v1/auth/refresh \
-H 'Authorization: Bearer YOUR_TOKEN'
🛣️ 路由配置
API 路由映射
| 路径前缀 | 目标服务 | 认证要求 |
|---|---|---|
/api/v1/health |
health-monitoring-service:8001 | ✅ JWT |
/api/v1/emotion |
companion-service:8002 | ✅ JWT |
/api/v1/dialogue |
companion-service:8002 | ✅ JWT |
/api/v1/care |
companion-service:8002 | ✅ JWT |
/api/v1/motion |
rehabilitation-service:8003 | ✅ JWT |
/api/v1/training |
rehabilitation-service:8003 | ✅ JWT |
/api/v1/game |
rehabilitation-service:8003 | ✅ JWT |
使用示例
# 健康监测API调用
curl -X GET "http://localhost:8000/api/v1/health/users/user123/metrics" \
-H "Authorization: Bearer YOUR_TOKEN"
# 情感分析API调用
curl -X POST "http://localhost:8000/api/v1/emotion/analyze" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"user_id": "user123",
"facial_image": "base64_image_data",
"voice_audio": "base64_audio_data"
}'
# 训练分析API调用
curl -X POST "http://localhost:8000/api/v1/motion/analyze" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"user_id": "user123",
"exercise_type": "arm_raise",
"motion_data": { ... }
}'
🔧 配置管理
Kong 配置
主要配置文件:kong.yml
- 服务定义:定义后端微服务
- 路由规则:URL路径到服务的映射
- 插件配置:CORS、认证、限流等
- 消费者管理:API客户端认证信息
插件配置
CORS 插件
plugins:
- name: cors
config:
origins:
- "http://localhost:3000"
- "https://admin.kangyang-robot.com"
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
限流插件
plugins:
- name: rate-limiting
config:
minute: 1000
hour: 10000
policy: local
JWT 认证插件
plugins:
- name: jwt
config:
uri_param_names: ["jwt"]
cookie_names: ["jwt"]
claims_to_verify: ["exp"]
📊 监控与日志
健康检查
# 网关整体健康状态
curl http://localhost:8000/health
# Kong状态检查
curl http://localhost:8001/status
# JWT服务健康检查
curl http://localhost:8080/api/v1/health
# Nginx状态
curl http://localhost:8080/nginx_status
Prometheus 指标
Kong自动暴露以下指标:
kong_http_requests_total- HTTP请求总数kong_request_latency_ms- 请求延迟kong_upstream_latency_ms- 上游服务延迟kong_nginx_connections- Nginx连接数
日志查看
# 查看所有服务日志
docker-compose logs -f
# 查看特定服务日志
docker-compose logs -f kong
docker-compose logs -f jwt-service
docker-compose logs -f nginx
🔒 安全特性
SSL/TLS 配置
- TLS 1.2/1.3 支持
- 安全密码套件
- HSTS 头部
- 自动HTTP重定向HTTPS
安全头部
X-Frame-Options: DENYX-Content-Type-Options: nosniffX-XSS-Protection: 1; mode=blockStrict-Transport-Security
IP 访问控制
- 管理接口IP白名单
- 地理位置过滤(可选)
- DDoS 防护
请求验证
- JWT Token 验证
- 请求大小限制
- 速率限制
- 输入验证
🚀 性能优化
连接池配置
services:
- name: health-monitoring-service
retries: 5
connect_timeout: 60000
write_timeout: 60000
read_timeout: 60000
缓存策略
- Redis 缓存集成
- 响应缓存
- 会话存储
负载均衡
- 轮询算法
- 健康检查
- 故障转移
🛠️ 故障排除
常见问题
1. Kong 无法启动
# 检查数据库连接
docker-compose logs kong-database
docker-compose logs kong-migration
# 重置数据库
docker-compose down -v
docker-compose up kong-database kong-migration
2. JWT认证失败
# 检查JWT服务
curl http://localhost:8080/api/v1/health
# 验证密钥配置
docker-compose exec jwt-service env | grep JWT_SECRET
3. 路由不工作
# 检查Kong配置
curl http://localhost:8001/services
curl http://localhost:8001/routes
# 重新加载配置
curl -X POST http://localhost:8001/config -F config=@kong.yml
调试模式
# 启用详细日志
export KONG_LOG_LEVEL=debug
docker-compose up -d kong
# 查看详细日志
docker-compose logs -f kong
📈 扩展部署
生产环境部署
- 使用真实SSL证书
# Let's Encrypt示例
certbot certonly --standalone -d api.kangyang-robot.com
- 数据库高可用
# 使用PostgreSQL集群
services:
kong-database:
image: postgres:13
deploy:
replicas: 3
- Redis 集群
# Redis集群配置
services:
redis-cluster:
image: redis:7-alpine
command: redis-server --cluster-enabled yes
Kubernetes 部署
# k8s部署示例
apiVersion: apps/v1
kind: Deployment
metadata:
name: kong-gateway
spec:
replicas: 3
selector:
matchLabels:
app: kong-gateway
template:
metadata:
labels:
app: kong-gateway
spec:
containers:
- name: kong
image: kong:3.4
ports:
- containerPort: 8000
- containerPort: 8001
📝 维护命令
# 备份Kong配置
curl http://localhost:8001/config > kong-backup.json
# 更新服务
docker-compose pull
docker-compose up -d
# 清理日志
docker-compose exec kong kong logs rotate
# 性能测试
ab -n 1000 -c 10 http://localhost:8000/api/v1/health
🤝 贡献指南
- Fork 项目
- 创建特性分支
- 提交更改
- 创建 Pull Request
📄 许可证
MIT License - 详见 LICENSE 文件