首页 > 解决方案 > 使用 RewritePath 刷新 Spring Cloud Gateway 失败

问题描述

我正在运行一个依赖于 Spring Cloud 配置服务器的 Spring Cloud Gateway 实例。我的应用程序以给定的以下配置启动。

  cloud:
    gateway:
      routes:
        - id: route-foo
          uri: lb://foo
          predicates:
            - Path=/api/foo/**
          filters:
            - name: RewritePath
              args:
                regexp: "/api/foo/(?<remaining>.*)"
                replacement: "/${remaining}"  

假设我对我的配置进行了修改并在下面添加了一条额外的路线

        - id: route-bar
          uri: lb://bar
          predicates:
            - Path=/api/bar/**
          filters:
            - name: RewritePath
              args:
                regexp: "/api/bar/(?<remaining>.*)"
                replacement: "/${remaining}"  

执行 POST 以http://localhost:8080/actuator/refresh返回以下错误。

500 Server Error for HTTP POST &#34;/actuator/refresh&#34; (Encoded)
java.lang.IllegalArgumentException: Could not resolve placeholder 'remaining' in value "/${remaining}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178)

看来 spring 正在尝试解析我的 RewritePath 替换并将其替换为环境变量。我有哪些选择?

标签: spring-bootspring-cloud-gateway

解决方案


您正在尝试替换配置中的变量。

有两种解决方案

转义替换语法(首选)

改变replacement: "/${remaining}"

replacement: "/$\\{remaining}"

RewriteGatewayFilterFactory在运行过滤器之前对配置进行替换



启用 ignoreUnresolvableNestedPlaceholders

@Bean
@Primary
public StandardReactiveWebEnvironment standardReactiveWebEnvironmentCustomizer(StandardReactiveWebEnvironment environment) {
    environment.setIgnoreUnresolvableNestedPlaceholders(true);
    return environment;
}

这将使所有无法解析的占位符单独留在您的配置中,并且在刷新期间不会失败。我建议不要使用这种方法,因为如果您依赖正确填充字段,它最终可能会将一些问题延迟到运行时。

从理论上讲,您应该能够使用PropertySourcesPlaceholderConfigurer完成相同的功能,但我很难让它合作。


推荐阅读