首页 > 解决方案 > spring 使用 k8s configmap

问题描述

我有一个 spring boot 服务,它目前使用.properties文件来使用 spring @Value 注释来使用变量。最近我们一直在将 Spring Boot 服务迁移到 K8 集群。这意味着,我们需要创建一个包含与该文件configmap.yml相同的所有属性的.properties文件。并且无论何时对属性进行更改,都必须在两个地方完成,即.properties用于本地开发的 configmap 和文件。所以我们必须为每个弹簧配置文件管理 2 个文件(configmap 和 .properties)。有一个更好的方法吗?我们使用 gitlab ci/cd 工具进行部署。

有没有办法在我们的机器上使用 configmap 而不是 properties 进行本地开发,这样我们就可以完全丢弃 .properties 文件而只维护 configmap?

管理 Spring Boot 应用程序属性的理想方式是什么?

示例 service-config-map.yaml

kind: ConfigMap 
apiVersion: v1 
metadata:
  name: myservice-config
data:
  server.port: "10300"
  spring.application.name: myserviceGateway
  myservice.application.name: helloworld
  myservice.server.apiContext: /api
  myservice.server.versionContext: /v
  myservice.current.version=2.0

属性文件application.properties

server.port=10300
spring.application.name=myserviceGateway
myservice.application.name=helloworld
myservice.server.apiContext=/api
myservice.server.versionContext=/v
myservice.current.version=2.0

标签: javaspringspring-bootkubernetesconfigmap

解决方案


Spring Cloud Kubernetes 项目使 Kubernetes在应用程序引导期间可用,并在观察到的 sConfigMap上检测到更改时触发 bean 或 Spring 上下文的热重载。ConfigMap

这里有一个例子

具有配置映射名称的引导 yaml 看起来像

spring:
  application:
    name: reload-example
  cloud:
    kubernetes:
      reload:
        enabled: true
        mode: polling
        period: 5000
      config:
        sources:
          - name: other
          - name: ${spring.application.name}

推荐阅读