如何在Maven构建中禁用Spring Cloud Kubernetes

3

运行Spring Boot 2.6.6和Spring Cloud 2021.0.1

我正在尝试将一个现有的服务迁移到Kubernetes,因此我添加了对 spring-cloud-starter-kubernetes-client-all 的依赖。默认情况下,我使用 kubernetes 配置文件,并且将 spring.cloud.kubernetes.enable=false,这旨在允许此服务在Kubernetes和传统环境中运行。

当在本地构建时,我的单元测试完成成功,但在我的Bitbucket管道中失败,并显示以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.cloud.kubernetes.commons.config.NamespaceResolutionFailedException: unresolved namespace

我怀疑这是因为Bitbucket Pipelines部署在Kubernetes上,而Spring不知何故检测到了它。我已尝试以下方法但均无效:
  • 在命令行中传递--define SPRING_CLOUD_KUBERNETES_ENABLED=false给Maven。
  • 将此设置为环境变量,例如export SPRING_CLOUD_KUBERNETES_ENABLED=false
  • 在命令行中传递--define spring.cloud.kubernetes.enabled=false给Maven。
我还在StackOverflow上查找类似问题并调查了代码,但也没有结果。实际引发问题的类是KubernetesClientConfigUtils,应该禁用它。
如果你能提供任何指导,我将不胜感激。
3个回答

5

Spring Cloud会在加载活动的spring profile配置之前检查应用是否运行在K8s环境中,并将kubernetes添加到活动配置文件中。在Hoxton SR10之前,先确定配置文件并加载bootstrap-<profile>.yml,然后再检查Kubernetes。如果在配置文件或maven pom属性中设置了spring.cloud.kubernetes.enabled,则会从那里获取。

由于Maven允许在命令行上设置系统属性,因此可以通过在命令行上设置来禁用Kubernetes检测:

mvn test -Dspring.cloud.kubernetes.enabled=false

surefire maven插件允许为所有测试设置系统属性,因此可以在surefire插件配置中将spring.cloud.kubernetes.enabled设置为false

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <spring.cloud.kubernetes.enabled>false</spring.cloud.kubernetes.enabled>
        </systemPropertyVariables>
    </configuration>
</plugin>

使用@Faron的方法可以在任何WebMvcTest单元测试中显式设置属性,从而在单个测试类上设置配置,例如:

@WebMvcTest(properties = { "spring.cloud.kubernetes.enabled=false" })

它也应该适用于其他加载Spring应用程序上下文的单元测试注释,例如WebFluxTest


如果您想更新您的答案,包括解决此问题的所有方法(包括我的解决方案),我将选择您的答案并点赞。回答自己的问题不会获得声望分。我还建议将最后一段移至开头,并重新表述以描述正在发生的事情(即没有责备)。 - Faron

1

在尝试了几种其他方法后,我终于找到了一个可行的方法。我使用以下方式将该属性添加到单元测试上下文中:

@WebMvcTest(properties = { "spring.cloud.kubernetes.enabled=false" })

这也适用于任何加载Spring应用程序上下文的单元测试注释,例如@WebFluxTest


1

在升级到Spring Boot 2.7.x和Spring Cloud 2021.x之后,我也遇到了这个问题:

NamespaceResolutionFailedException: unresolved namespace

我的解决方法是在测试resources文件夹中添加一个bootstrap.yml文件,其中包含以下内容:
spring:
  cloud:
    compatibility-verifier.enabled: false
    kubernetes:
      enabled: false
      reload.enabled: false
      discovery.enabled: false

(如果存在)请从application.yml中删除它。

来自文档:

https://www.baeldung.com/spring-cloud-bootstrap-properties

https://github.com/spring-cloud/spring-cloud-kubernetes/issues?q=unresolved+namespace


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接