2 Predicate

本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金

Predicate

Predicate是java 8提供的一个函数式接口,它允许接收一个参数并返回一个布尔值,可以用于条件过滤,请求cas的校验。

指定时间规则匹配路由

  • 请求在指定日期之前 对应BeforeRoutePredicateFactory
  • 请求在指定日期之后 对应AfterRoutePredicateFactory
  • 请求在指定的两个日期之间 对应 BetweenRoutePredicateFactory
spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
复制代码

Cookie匹配路由

对应CookieRoutePredicateFactory

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, xpp
复制代码

当前请求需要携带一个name=chocolate value为xpp才能路由到example.org

Header匹配路由

对应HeaderRoutePredicateFactory,判断请求中Header头消息对应的name和value与Predicate配置的值是否匹配,value也是正则匹配形式

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+
复制代码

请求中Header头的name=X-Request-Id value根据正则表达式匹配\d+ ,也就是匹配1个以上的数字。

Host匹配路由

HTTP请求会携带一个Host字段,这个字段表示请求的服务器地址,对应HostRoutePredicateFactory

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org
复制代码

host可以配置一个列表,列表中的每个元素通过逗号分隔。当前请求中的host的值符合**.somehost.org, **.anotherhost.org时候,才会路由到example.org

请求方法匹配路由

对应MethodRoutePredicateFactory 根据HTTP请求的Method属性来匹配以实现路由

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

如果请求的方式为GET或POST请求,会路由到example.org

请求路径匹配路由

对应PathRoutePredicateFactory

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}
复制代码

{segment}为特殊的占位符,/*表示单层路径匹配,/**表示多层路径匹配。匹配请求的URI为/red/* ,/blue/* 时,才会转发到example.org

总结一下,我们这篇文章主要讲了gateway的谓词部分,谓词是java8进入的函数式接口,提供断言功能。可以匹配HTTP请求中的任何内容。如果Predicate集合判断结果为true,则意味着请求会被当前Router进行转发。

然后谓词的类型大概有按照指定时间规则匹配路由,按照Cookie匹配路由,按照Header匹配路由,按照Host匹配路由,按照请求方法匹配路由等待。

我们在合适的场合使用合适的谓词路由规则,简化我们的代码开发,让gateway网关真正起到路由转发的作用,gateway网关的本质是对请求进行路由转发以及对请求前置和后置的过滤,在下篇文章中我们会对过滤器这一部分的内容进行讲解,如果这篇文章对你有帮助的话,不要忘了给我点赞留言哦,嘿嘿,您的赞和评论是对我大力的支持,我们一起学习好gateway网关,以便在工作中能够灵活运用,让gateway网关真正发挥它的作用。

参考:docs.spring.io/spring-clou…

猜你喜欢

转载自juejin.im/post/7019536777874505759