fengling-console/docs/testing-guide.md

7.8 KiB
Raw Blame History

YARP Gateway 测试指南

1. 数据库准备

使用EF Core Migrations初始化数据库

项目使用 EF Core 管理数据库,已生成迁移脚本位于 sql/init.sql

# 连接到PostgreSQL并执行迁移脚本
psql -h 192.168.100.10 -U postgres -d fengling_gateway -f sql/init.sql

如果数据库不存在,先创建数据库:

psql -h 192.168.100.10 -U postgres -c "CREATE DATABASE fengling_gateway;"

验证数据

psql -h 192.168.100.10 -U postgres -d fengling_gateway -c "\dt"

应该看到3个表

  • Tenants
  • TenantRoutes
  • ServiceInstances

2. 启动网关

cd /Users/movingsam/Fengling.Refactory.Buiding/src/YarpGateway
dotnet run

网关将在 http://localhost:8080 启动。

3. 测试API接口

3.1 创建租户

curl -X POST http://localhost:8080/api/gateway/tenants \
  -H "Content-Type: application/json" \
  -d '{
    "tenantCode": "customerA",
    "tenantName": "客户A"
  }'

响应示例:

{
  "id": 1738377721234,
  "tenantCode": "customerA",
  "tenantName": "客户A",
  "status": 1,
  "createdBy": null,
  "createdTime": "2026-02-01T20:08:41.234Z",
  "updatedBy": null,
  "updatedTime": null,
  "isDeleted": false,
  "version": 0
}

3.2 查看所有租户

curl http://localhost:8080/api/gateway/tenants

3.3 为租户创建路由

curl -X POST http://localhost:8080/api/gateway/tenants/customerA/routes \
  -H "Content-Type: application/json" \
  -d '{
    "serviceName": "product",
    "pathPattern": "/api/product/{**catch-all}"
  }'

响应示例:

{
  "id": 1738377722345,
  "tenantCode": "customerA",
  "serviceName": "product",
  "clusterId": "customerA-product",
  "pathPattern": "/api/product/{**catch-all}",
  "priority": 0,
  "status": 1
}

3.4 查看租户路由

curl http://localhost:8080/api/gateway/tenants/customerA/routes

3.5 添加服务实例

curl -X POST http://localhost:8080/api/gateway/clusters/customerA-product/instances \
  -H "Content-Type: application/json" \
  -d '{
    "destinationId": "product-1",
    "address": "http://localhost:8001",
    "weight": 1
  }'

3.6 查看Cluster实例

curl http://localhost:8080/api/gateway/clusters/customerA-product/instances

3.7 重新加载配置

curl -X POST http://localhost:8080/api/gateway/reload

响应:

{
  "message": "Config reloaded successfully"
}

4. JWT测试

4.1 生成测试JWT

使用 https://jwt.io/ 生成测试JWT

Header:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload:

{
  "tenant": "customerA",
  "sub": "123456",
  "unique_name": "张三",
  "role": ["admin", "user"],
  "exp": 1738369200
}

Secret (示例密钥):

your-secret-key-at-least-32-bytes-long

4.2 测试JWT解析

JWT_TOKEN="your-generated-jwt-token"

curl -X GET http://localhost:8080/api/product/list \
  -H "Authorization: Bearer $JWT_TOKEN"

4.3 验证Header传递

创建一个测试服务来接收请求:

创建测试服务 (test-service.js):

const http = require('http');

const server = http.createServer((req, res) => {
  console.log('收到请求:');
  console.log('URL:', req.url);
  console.log('Headers:', req.headers);

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    message: '请求成功',
    tenantId: req.headers['x-tenant-id'],
    userId: req.headers['x-user-id'],
    userName: req.headers['x-user-name'],
    roles: req.headers['x-roles']
  }));
});

server.listen(8001, () => {
  console.log('测试服务运行在 http://localhost:8001');
});

启动测试服务:

node test-service.js

5. 负载均衡测试

5.1 添加多个服务实例

# 实例1
curl -X POST http://localhost:8080/api/gateway/clusters/customerA-product/instances \
  -H "Content-Type: application/json" \
  -d '{
    "destinationId": "product-1",
    "address": "http://localhost:8001",
    "weight": 10
  }'

# 实例2
curl -X POST http://localhost:8080/api/gateway/clusters/customerA-product/instances \
  -H "Content-Type: application/json" \
  -d '{
    "destinationId": "product-2",
    "address": "http://localhost:8002",
    "weight": 5
  }'

5.2 并发测试

for i in {1..20}; do
  curl -X GET http://localhost:8080/api/product/list \
    -H "Authorization: Bearer $JWT_TOKEN" &
done
wait

观察日志输出,验证请求是否按权重分配到不同实例。

6. 日志查看

查看网关日志

控制台会输出实时日志,包括:

  • JWT解析日志
  • 路由选择日志
  • 负载均衡选择日志

日志文件位置

/Users/movingsam/Fengling.Refactory.Buiding/src/YarpGateway/logs/gateway-YYYYMMDD.log

7. 故障排查

问题1: 无法连接数据库

测试连接:

psql -h 192.168.100.10 -U postgres -d fengling_gateway

检查配置:

  • 确认 appsettings.json 中的连接字符串正确
  • 确认 PostgreSQL 已启动并可访问

问题2: 路由404

检查租户配置:

curl http://localhost:8080/api/gateway/tenants

检查路由配置:

curl http://localhost:8080/api/gateway/tenants/customerA/routes

检查实例配置:

curl http://localhost:8080/api/gateway/clusters/customerA-product/instances

问题3: JWT解析失败

验证JWT格式:

echo "your.jwt.token" | cut -d'.' -f2 | base64 -d

检查日志中的错误信息

问题4: 数据库迁移失败

手动执行SQL脚本:

psql -h 192.168.100.10 -U postgres -d fengling_gateway -f sql/init.sql

检查迁移历史:

SELECT * FROM "__EFMigrationsHistory";

8. 使用Docker Compose

如果使用Docker Compose部署

cd /Users/movingsam/Fengling.Refactory.Buiding/docker
docker-compose up -d

查看日志:

docker-compose logs -f gateway

9. 清理

停止网关

Ctrl+C 停止 dotnet run

删除数据库(如果需要)

psql -h 192.168.100.10 -U postgres -c "DROP DATABASE fengling_gateway;"

10. 创建示例数据

创建完整示例数据

# 1. 创建租户
curl -X POST http://localhost:8080/api/gateway/tenants \
  -H "Content-Type: application/json" \
  -d '{"tenantCode": "customerB", "tenantName": "客户B"}'

# 2. 创建订单服务路由
curl -X POST http://localhost:8080/api/gateway/tenants/customerA/routes \
  -H "Content-Type: application/json" \
  -d '{"serviceName": "order", "pathPattern": "/api/order/{**catch-all}"}'

# 3. 为客户B创建产品服务
curl -X POST http://localhost:8080/api/gateway/tenants/customerB/routes \
  -H "Content-Type: application/json" \
  -d '{"serviceName": "product", "pathPattern": "/api/product/{**catch-all}"}'

# 4. 为客户B产品服务添加实例
curl -X POST http://localhost:8080/api/gateway/clusters/customerB-product/instances \
  -H "Content-Type: application/json" \
  -d '{"destinationId": "product-1", "address": "http://localhost:8003", "weight": 1}'

验证配置

# 查看所有租户
curl http://localhost:8080/api/gateway/tenants | jq

# 查看客户A的所有路由
curl http://localhost:8080/api/gateway/tenants/customerA/routes | jq

# 查看客户A产品服务的所有实例
curl http://localhost:8080/api/gateway/clusters/customerA-product/instances | jq

11. EF Core Migrations管理

添加新迁移

cd /Users/movingsam/Fengling.Refactory.Buiding/src/YarpGateway
dotnet ef migrations add AddNewFeature

生成SQL脚本

dotnet ef migrations script --context GatewayDbContext --output ../sql/migration_$(date +%Y%m%d).sql

应用迁移到数据库

dotnet ef database update --context GatewayDbContext

回滚迁移

dotnet ef database update 20260201120312_InitialCreate --context GatewayDbContext