繁体   English   中英

spring 使用 k8s configmap

[英]Consume k8s configmap in spring

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

有没有办法在我们的机器中使用 configmap 而不是属性来进行本地开发,这样我们就可以完全丢弃 .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

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

这里有一个例子

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

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

是的,这是可行的。

首先,您需要一个 bean 从 yaml 中占位,例如:

@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
    yaml.setResources(new ClassPathResource(CONF_FILE));
    propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
    return propertySourcesPlaceholderConfigurer;
}

然后您可以将任何标准服务注释为:

    @Service
@EnableConfigurationProperties
@ConfigurationProperties(prefix="service-config-map")
public class ConfigMapConfigService {
...

根据您对集群的访问类型,您可以使用 K8s API 通过 HTTP 检索资源。 例如,您可以使用某种脚本从集群中提取 configmap 并将其解析为 yaml(默认情况下它在 json 中,不确定是否支持 yaml 输出,但还没有真正测试过)。

在此处查看更多信息: https : //docs.openshift.com/container-platform/3.7/rest_api/api/v1.ConfigMap.html#Get-api-v1-namespaces-namespace-configmaps-name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM