spring boot 在 k8s 使用 kubernets configmap作為配置中心

spring boot 在 k8s 使用 kubernets configmap作為配置中心

引用& 參考

https://amit4aws.medium.com/spring-cloud-kubernetes-configwatcher-7a206fe269e3

https://github.com/spring-cloud/spring-cloud-kubernetes#kubernetes-propertysource-implementations

https://github.com/amit4aws/ConfigWatcher/tree/main/demo

https://www.cnblogs.com/larrydpk/p/13611431.html

spring boot 服務程序讀取 kubernets configmap 配置

 <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-kubernetes-config</artifactId>
   <version>1.1.9.RELEASE</version>
 </dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Spring boot 版本使用:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.11.RELEASE</version>

創(chuàng)建項目配置文件 bootstrap.yml

spring:
  application:
    name: projectName
  cloud:
    kubernetes:
      reload:
        enabled: true
        strategy: refresh
        mode: event
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    restart:
      enabled: true

主要說明:

(1) spring.cloud.kubernetes.reload.enabled=true需要打開刷新功能;

(2) 加載策略strategy

  • refresh:只對特定的配置生效,有注解@ConfigurationProperties@RefreshScope
  • restart_context:整個Spring Context會優(yōu)雅重啟,里面的所有配置都會重新加載。(考慮是否可在線使用此策略)

需要打開actuator endpoint,所以要配置management.endpoint。actuator依賴:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • shutdown:重啟容器。

(3)模式mode

  • 事件Event:會通過k8s API監(jiān)控ConfigMap的變更,讀取配置并生效。
  • Polling:定期查看是否有變化,有變化則觸發(fā),默認為15秒。

以上配置 發(fā)現 并為配置 從何處的configmap讀取, 是通過 Spring Cloud Kubernetes Configuration Watcher Controller 可以實現監(jiān)聽configmap的變化后重新加載應用程序上下文和訂閱哪些ConfigMap事件以及需要更新哪些服務

https://github.com/spring-cloud/spring-cloud-kubernetes#spring-cloud-kubernetes-configuration-watcher

Spring Cloud Kubernetes Configuration Watcher Controller (擴展,可忽略實際已部署在k8s集群下)

一、k8s 下部署

apiVersion: v1
kind: ServiceAccount
metadata:
  name: ns-admin
  namespace: ns
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: ns-admin-role
  namespace: ns
rules:
- apiGroups:
  - ""
  resources:
  - namespaces
  - endpoints
  - services
  - nodes
  - nodes/proxy
  - pods
  - configmaps
  verbs:
  - list
  - get
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ns-admin-role-binding
  namespace: ns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: ns-admin-role
subjects:
- kind: ServiceAccount
  name: ns-admin
  namespace: ns
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: spring-cloud-kubernetes-configuration-watcher-deployment
  namespace: ns
spec:
  selector:
    matchLabels:
      app: spring-cloud-kubernetes-configuration-watcher
  template:
    metadata:
      labels:
        app: spring-cloud-kubernetes-configuration-watcher
    spec:
      serviceAccountName: ns-admin
      containers:
      - name: spring-cloud-kubernetes-configuration-watcher
        image: springcloud/spring-cloud-kubernetes-configuration-watcher:2.0.2
        imagePullPolicy: IfNotPresent
        readinessProbe:
          httpGet:
            port: 8888
            path: /actuator/health/readiness
        livenessProbe:
          httpGet:
            port: 8888
            path: /actuator/health/liveness
        ports:
        - containerPort: 8888

Spring Cloud Kubernetes Configuration Watcher will react to changes in ConfigMaps with a label of spring.cloud.kubernetes.config with the value true or any Secret with a label of spring.cloud.kubernetes.secret with the value true. If the ConfigMap or Secret does not have either of those labels or the values of those labels is not true then any changes will be ignored.

The labels Spring Cloud Kubernetes Configuration Watcher looks for on ConfigMaps and Secrets can be changed by setting spring.cloud.kubernetes.configuration.watcher.configLabel and spring.cloud.kubernetes.configuration.watcher.secretLabel respectively.

If a change is made to a ConfigMap or Secret with valid labels then Spring Cloud Kubernetes Configuration Watcher will take the name of the ConfigMap or Secret and send a notification to the application with that name.

The HTTP implementation is what is used by default. When this implementation is used Spring Cloud Kubernetes Configuration Watcher and a change to a ConfigMap or Secret occurs then the HTTP implementation will use the Spring Cloud Kubernetes Discovery Client to fetch all instances of the application which match the name of the ConfigMap or Secret and send an HTTP POST request to the application’s actuator /refresh endpoint. By default it will send the post request to /actuator/refresh using the port registered in the discovery client.

配置configmap

通過上述可以得知 按照默認configmap 配置 需要加上label 標簽 spring.cloud.kubernetes.config = ture

并且在同一namespace下與服務同名

apiVersion: v1
kind: ConfigMap
metadata:
  name: projectName
  namespace: ns
  labels:
    spring.cloud.kubernetes.config: "true"
data:
  application.yml: |-
    server:
      port: 80
    
    spring:
      datasource:
        # 使用阿里的Druid連接池
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        # 填寫你數據庫的url、登錄名、密碼和數據庫名
        url: url
        username: username
        password: password
        druid:
          # 連接池的配置信息
          # 初始化大小,最小,最大
          initial-size: 10
          min-idle: 10
          maxActive: 30
          validationQuery: SELECT 1
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          time-between-eviction-runs-millis: 60000
          min-evictable-idle-time-millis: 180000    

If the values are set to true then Configuration Watcher will take the name of the ConfigMap or Secret and will send a notification to the application available with the same name.

應用如何應用自動刷新配置

自動重啟應用

修改 bootstrap.yml

spring:
  cloud:
    kubernetes:
      reload:
        strategy: restart_context

整個Spring Context會優(yōu)雅重啟,里面的所有配置都會重新加載。

熱更新配置

spring:
  cloud:
    kubernetes:
      reload:
        strategy: refresh

只對特定的配置生效,有注解@ConfigurationProperties@RefreshScope

以durid數據庫連接為例

@Configuration
@Slf4j
@RefreshScope
public class DataSourceConfig {

    @Bean
    @RefreshScope
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        log.info("Init DruidDataSource");
        return new DruidDataSourceBuilder().build();
    }
}

todo : 采用策略

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容