首页 > 解决方案 > 如何在 Spring Cloud Gateway 中为发现定位器编写复杂的谓词?

问题描述

我想自定义发现定位器行为。例如,在我的案例中,路由从gateway_host/prohibitions名为prohibitions-ui. 为此,我正在使用此配置:

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          filters: PreserveHostHeader
          include-expression: serviceId.endsWith('-UI')
          predicates: Path='/'+serviceId.substring(0,serviceId.indexOf('-UI'))+'/**'

然后报错:

Failed to bind properties under 'spring.cloud.gateway.discovery.locator.predicates' to java.util.List<org.springframework.cloud.gateway.handler.predicate.PredicateDefinition>:

Reason: failed to convert java.lang.String to org.springframework.cloud.gateway.handler.predicate.PredicateDefinition

我认为由于传递给substring方法的两个参数而导致此错误上升。如果我将方法调用更改为substring(0)然后应用程序成功启动,但这样的配置对我来说没有意义: predicates: Path='/'+serviceId.substring(0)+'/**'

标签: springspring-cloudspring-cloud-gateway

解决方案


该属性spring.cloud.gateway.discovery.locator.predicates引用谓词定义列表,请参阅org.springframework.cloud.gateway.discovery.DiscoveryLocatorProperties。您指定的内容将转换为 a String,因此无法转换为所需的类型。

您可以尝试按如下方式指定谓词:

spring:
  cloud:
    gateway:
      discovery:
        locator:
          predicates: 
          - name: Path
            args:
              pattern: '/'+serviceId.substring(0,serviceId.indexOf('-UI'))+'/**'

推荐阅读