一 方案概述
利用Kubernetes原生configmap/secret 资源作为配置中心,不用关注服务可用性,即网络问题,同时也不用引入新的组建,造成运维成本。
二 SpringCloudKubernetes 配置中心方案
2.1 方案介绍
2.1.1 spring-cloud-starter-kubernetes-config
spring-cloud-starter-kubernetes-config是spring-cloud-starter-kubernetes下的一个库,作用是将kubernetes的configmap与SpringCloud Config结合起来。 spring-boot-actuator
/ spring-boot-actuator-autoconfigure
两个包的引入,使得应用可以进行热更新,当configmap/secret发生变更的时候,可以不重启Pod或进程进行热变更配置。
2.1.2 功能简介
SpringCloud Kubernetes Config 组件主要提供以下几种功能:
- 实时监控 ConfigMap、Secret 配置变化从而更新服务配置。
- 定时轮询加载 ConfigMap、Secret 配置从而更新服务配置。
2.2 配置发现过程
本质上配置管理利用了etcd的存储,首先是应用调用 spring-cloud-kubernetes-config 包,其调用了底层java实现的kubernetes-client,通过调用k8s api来实现从etcd中获取configmap和secret资源信息。
2.3 方案特点
- 优点:
- 使用K8s内置资源,无需考虑引入配置中心服务,不用考虑配置中心服务高可用。
- 云原生架构,配置中心下沉至基础设施层,无需业务代码耦合,减少成本。
- 不足:
- dev/test 环境也需要上K8s,确保环境一致性。
- 需要将配置资源configmap/secret引入到GitOps流程中。
三 实战
新建 bootstrap.yml 配置文件,最终的application.yaml 使用k8s 的configmap/secret资源。
spring: profiles: ## 如果 PROFILE 为空,则使用dev active: ${PROFILE:dev} application: name: springboot-config cloud: # 监控k8s configmap/secret api获取配置 kubernetes: reload: #自动更新配置的开关设置为打开 enabled: true #更新配置信息的模式:polling是主动拉取,event是事件通知 mode: polling #主动拉取的间隔时间是500毫秒 period: 500 #是否监控 Secret 的更改来执行更新 monitoring-secrets: true config: namespace: springconfig name: ${spring.application.name}-cm # 模式仅启动configmap获取,启用secret使用enable-api secrets: enable-api: true namespace: springconfig name: ${spring.application.name}-secret #labels: #指定 Label 标签名词,根据这个标签筛选 Secret,读取其中配置 # secret: enabled #自定义的 Label management: endpoint: restart: enabled: true health: enabled: true info: enabled: true 复制代码
在此模拟三种获取配置方式:
ConfigurationProperties Environment
3.1 Configmap
3.1.1 value方式
// -----------------value configmap----------------- @Value("${config.applicationVersion}") private String applicationVersion; @Value("${config.app.domain}") private String domain;