图片预览

滚轮缩放 · 拖动移动 · Esc 关闭

Skip to content

网关路由配置指南 ​

一、概述 ​

配置 pigx-gateway 服务,使其能够路由到 pigx-standard 服务。

二、网关基础信息 ​

  • Gateway 服务名: pigx-gateway
  • Gateway 端口: 9999
  • Standard 服务名: pigx-standard-biz (注册到Nacos时使用此名称)
  • Standard 端口: 6064

三、路由配置方式 ​

PigX Gateway 使用 Nacos 配置中心进行动态路由配置。

配置位置 ​

在 Nacos 配置中心添加路由配置:

命名空间: 当前环境(如 dev) Data ID: pigx-gateway-dev.yml (根据环境调整) Group: DEFAULT_GROUP

路由配置示例 ​

yaml
spring:
  cloud:
    gateway:
      routes:
        # pigx-standard 服务路由配置
        - id: pigx-standard
          uri: lb://pigx-standard-biz
          predicates:
            - Path=/standard/**
          filters:
            - StripPrefix=1
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10
                redis-rate-limiter.burstCapacity: 20
            # 可选:添加响应头
            - AddResponseHeader=X-Response-Default-Foo, Default-Bar

        # 或者使用更细粒度的路由
        - id: pigx-standard-user
          uri: lb://pigx-standard-biz
          predicates:
            - Path=/standard/user/**
          filters:
            - StripPrefix=1

        - id: pigx-standard-api
          uri: lb://pigx-standard-biz
          predicates:
            - Path=/standard/api/**
          filters:
            - StripPrefix=1

四、配置说明 ​

1. id ​

路由的唯一标识符,建议使用服务名。

2. uri ​

目标服务地址:

  • lb://pigx-standard-biz: 使用负载均衡,从 Nacos 获取服务实例
  • pigx-standard-biz: 服务在 Nacos 中注册的名称(来自 application.yml 中的 spring.application.name)

3. predicates(断言) ​

匹配请求的条件:

  • Path=/standard/**: 匹配所有以 /standard/ 开头的请求

常用断言:

yaml
predicates:
  - Path=/standard/**                    # 路径匹配
  - Method=GET,POST                      # HTTP方法匹配
  - Header=X-Request-Id, \d+             # 请求头匹配
  - Query=token                          # 查询参数匹配
  - After=2023-01-01T00:00:00+08:00[Asia/Shanghai]  # 时间匹配

4. filters(过滤器) ​

对请求/响应进行处理:

  • StripPrefix=1: 去掉路径前缀

    请求: /standard/user/list
    转发: /user/list (去掉 /standard)
  • RequestRateLimiter: 限流配置

    yaml
    redis-rate-limiter.replenishRate: 10   # 每秒补充令牌数
    redis-rate-limiter.burstCapacity: 20   # 令牌桶容量
  • AddResponseHeader: 添加响应头

  • AddRequestHeader: 添加请求头

  • RewritePath: 重写路径

五、访问示例 ​

配置后的访问方式 ​

bash
# 原始 Standard 服务地址(直接访问,不推荐)
http://localhost:6064/user/list

# 通过 Gateway 访问(推荐)
http://localhost:9999/standard/user/list

# 实际转发
Gateway收到: /standard/user/list
经过 StripPrefix=1: /user/list
转发到: http://pigx-standard-biz:6064/user/list

完整请求流程 ​

客户端
  ↓
  | http://localhost:9999/standard/user/list
  ↓
Gateway (9999)
  ↓ 验证JWT令牌
  ↓ 限流检查
  ↓ 路由匹配: /standard/**
  ↓ 去除前缀: StripPrefix=1
  ↓ 负载均衡: lb://pigx-standard-biz
  ↓
Standard Service (6064)
  ↓ /user/list
  ↓ 权限验证
  ↓ 业务处理
  ↓
返回响应

六、Nacos 配置步骤 ​

步骤1:登录 Nacos 控制台 ​

URL: http://localhost:8848/nacos
用户名: nacos
密码: nacos

步骤2:进入配置管理 ​

配置管理 → 配置列表 → 选择命名空间(dev)

步骤3:找到或创建 Gateway 配置 ​

Data ID: pigx-gateway-dev.ymlGroup: DEFAULT_GROUP

步骤4:添加路由配置 ​

在现有配置中添加 pigx-standard 的路由:

yaml
# 在 spring.cloud.gateway.routes 数组中添加
spring:
  cloud:
    gateway:
      routes:
        # ... 其他服务的路由 ...

        # 添加 pigx-standard 路由
        - id: pigx-standard
          uri: lb://pigx-standard-biz
          predicates:
            - Path=/standard/**
          filters:
            - StripPrefix=1
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10
                redis-rate-limiter.burstCapacity: 20

步骤5:发布配置 ​

点击"发布"按钮,Gateway 会自动重新加载配置(无需重启)。

七、验证路由配置 ​

1. 查看 Nacos 服务列表 ​

服务管理 → 服务列表 → 查看 pigx-standard-biz

确认服务已注册,状态为"健康"。

2. 测试路由 ​

bash
# 健康检查(不需要认证)
curl http://localhost:9999/standard/actuator/health

# 业务接口(需要认证)
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
     http://localhost:9999/standard/user/list

3. 查看 Gateway 日志 ​

bash
# 在 logs 目录查看 Gateway 日志
tail -f logs/pigx-gateway/info.log

关键日志:

[RouteDefinitionRouteLocator] : Loaded RoutePredicateFactory [Path]
[RouteDefinitionRouteLocator] : Loaded FilterFactory [StripPrefix]

八、高级配置 ​

1. 动态路由刷新 ​

使用 Spring Cloud Gateway 的动态路由功能,可以通过 API 动态添加/删除路由:

java
@RestController
@RequestMapping("/gateway/routes")
public class GatewayRouteController {

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    @PostMapping
    public Mono<ResponseEntity<Object>> addRoute(@RequestBody RouteDefinition definition) {
        return routeDefinitionWriter.save(Mono.just(definition))
                .then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build())));
    }
}

2. 自定义过滤器 ​

java
@Component
public class StandardAuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 自定义逻辑
        String path = exchange.getRequest().getURI().getPath();
        if (path.startsWith("/standard/")) {
            // 添加自定义处理
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}

3. 路由断言工厂 ​

java
@Component
public class StandardRoutePredicateFactory
        extends AbstractRoutePredicateFactory<StandardRoutePredicateFactory.Config> {

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            // 自定义断言逻辑
            return true;
        };
    }

    public static class Config {
        private String pattern;
        // getters and setters
    }
}

九、常见问题 ​

Q1: 404 Not Found ​

原因:

  • 路由配置不正确
  • 服务未注册到 Nacos
  • 路径前缀处理不正确

解决:

bash
# 1. 检查服务注册
curl http://localhost:8848/nacos/v1/ns/instance/list?serviceName=pigx-standard-biz

# 2. 检查路由配置
curl http://localhost:9999/actuator/gateway/routes

# 3. 查看 Gateway 日志

Q2: 503 Service Unavailable ​

原因:

  • Standard 服务未启动
  • 服务健康检查失败
  • Nacos 无法连接

解决:

bash
# 检查 Standard 服务状态
curl http://localhost:6064/actuator/health

# 检查 Nacos 连接
curl http://localhost:8848/nacos/v1/console/health/liveness

Q3: 401 Unauthorized ​

原因:

  • JWT 令牌无效
  • 未携带 Authorization 头
  • 令牌已过期

解决:

bash
# 1. 登录获取新令牌
curl -X POST http://localhost:9999/auth/oauth/token \
  -d "username=admin&password=123456&grant_type=password"

# 2. 使用新令牌访问
curl -H "Authorization: Bearer NEW_TOKEN" \
     http://localhost:9999/standard/user/list

Q4: 429 Too Many Requests ​

原因:

  • 触发限流

解决: 调整 Nacos 配置中的限流参数:

yaml
redis-rate-limiter.replenishRate: 100  # 增大令牌补充速率
redis-rate-limiter.burstCapacity: 200  # 增大令牌桶容量

十、参考配置模板 ​

完整 Gateway 配置示例 ​

yaml
spring:
  cloud:
    gateway:
      # 全局配置
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"
            allowedHeaders: "*"
            allowCredentials: true

      # 路由配置
      routes:
        # pigx-standard 服务
        - id: pigx-standard
          uri: lb://pigx-standard-biz
          predicates:
            - Path=/standard/**
          filters:
            - StripPrefix=1
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10
                redis-rate-limiter.burstCapacity: 20
            # 添加响应时间统计
            - name: Hystrix
              args:
                name: fallbackcmd
                fallbackUri: forward:/fallback

        # 其他服务...
        - id: pigx-upms
          uri: lb://pigx-upms-biz
          predicates:
            - Path=/admin/**
          filters:
            - StripPrefix=1

十一、检查清单 ​

  • [ ] Nacos 配置中已添加 pigx-standard 路由
  • [ ] 路由 predicates 配置正确(Path=/standard/**)
  • [ ] 路由 filters 配置正确(StripPrefix=1)
  • [ ] Standard 服务已在 Nacos 注册
  • [ ] Gateway 配置已刷新(或重启)
  • [ ] 可以通过 Gateway 访问 Standard 服务
  • [ ] JWT 认证正常工作
  • [ ] 限流配置生效

文档版本: v1.0 创建时间: 2025-12-16 最后更新: 2025-12-16