Gateway Method 路由断言工厂

Method 路由断言工厂接收一个方法参数,该参数可以指定一个或多个 HTTP 请求方法,多个方法使用逗号(,)进行分割。例如:

spring:
 cloud:
   gateway:
     routes:
     - id: method_route
       uri: https://example.org
       predicates:
       - Method=GET,POST

上面配置,如果请求方法是 GET 或 POST,该路由将与之匹配。

示例

将“Gateway 搭建网关服务”项目的配置文件 bootstrap.yml 内容使用如下配置替换:

server:
  # 网关端口
  port: 9000

spring:
  application:
    # 服务名称
    name: gateway-demo01
  cloud:
    # nacos
    nacos:
      discovery:
        server-addr: localhost:8848
        username: nacos
        password: nacos
        group: DEFAULT_GROUP

    # 网关路由配置
    gateway:
      # 网关路由配置
      routes:
        # 路由id,自定义,只要唯一集合
        - id: service-order
          # 路由的目标地址,lb 就是负载均衡,后面跟服务名
          # 需要集成 nacos 等服务注册中心
          uri: lb://service-order
          # 路由断言,也就是判断请求是否符合路由规则的条件
          predicates:
            # Method断言:匹配请求方法为 GET 的请求
            - Method=GET

修改好配置后,重启网关服务,使用 Postman 访问订单服务。如下图:

Gateway Method 路由断言工厂

如果将 Method 断言改为:

Method=POST

重启网关服务,继续访问接口,如下图:

Gateway Method 路由断言工厂

源码分析

下面是 Method 路由断言工厂的源码:

package org.springframework.cloud.gateway.handler.predicate;

//...

public class MethodRoutePredicateFactory extends AbstractRoutePredicateFactory<MethodRoutePredicateFactory.Config> {

    public static final String METHOD_KEY = "method";

    public MethodRoutePredicateFactory() {
       super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
       return Arrays.asList(METHOD_KEY);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
       return exchange -> {
          // 从请求对象中获取方法信息
          HttpMethod requestMethod = exchange.getRequest().getMethod();
          // 将请求的方法和配置的方法进行比较
          return requestMethod == config.getMethod();
       };
    }

    public static class Config {
       private HttpMethod method;

       // 配置信息
    }
}
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号