Springboot整合Spring Cloud Kubernetes讀取ConfigMap,支援自動刷新配置

1 前言

歡迎訪問南瓜慢說 www.pkslow.com獲取更多精彩文章!

Docker & Kubernetes相關文章:容器技術

之前介紹了Spring Cloud Config的用法,但對於Kubernetes應用,可能會需要讀取ConfigMap的配置,我們看看Springboot是如何方便地讀取ConfigMapSecret

2 整合Spring Cloud Kubenetes

Spring Cloud Kubernetes提供了Spring Cloud應用與Kubernetes服務關聯,我們也可以自己寫Java程式來獲取Kubernetes的特性,但Spring又為我們做了。

2.1 項目程式碼

引入依賴:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-kubernetes-config</artifactId>
</dependency>

只需要Springboot WebSpring Cloud Kubernetes Config即可,很簡單。

Springboot啟動類:

@SpringBootApplication
public class ConfigMapMain {
    public static void main(String[] args) {
        SpringApplication.run(ConfigMapMain.class, args);
    }
}

準備一個EndPoint來展示所讀到的配置資訊:

@RestController
public class PkslowController {
    @Value("${pkslow.age:0}")
    private Integer age;

    @Value("${pkslow.email:null}")
    private String email;

    @Value("${pkslow.webSite:null}")
    private String webSite;

    @Value("${pkslow.password:null}")
    private String password;

    @GetMapping("/pkslow")
    public Map<String, String> getConfig() {
        Map<String, String> map = new HashMap<>();
        map.put("age", age.toString());
        map.put("email", email);
        map.put("webSite", webSite);
        map.put("password", password);
        return map;
    }
}

默認是為空的,password是從Secret讀取,其它從ConfigMap讀取。

應用的配置文件如下:

server:
  port: 8080
spring:
  application:
    name: spring-cloud-kubernetes-configmap
  cloud:
    kubernetes:
      config:
        name: spring-cloud-kubernetes-configmap

這裡的spring.cloud.kubernetes.config.name是重點,後續要通過它來找ConfigMap

加密密碼:

$ echo -n "pkslow-pass" | base64 
cGtzbG93LXBhc3M=

創建Kubernetes Secret

kind: Secret
apiVersion: v1
metadata:
  name: spring-cloud-kubernetes-secret
  namespace: default
data:
  pkslow.password: cGtzbG93LXBhc3M=
type: Opaque

ConfigMap的內容如下:

kind: ConfigMap
apiVersion: v1
metadata:
  name: spring-cloud-kubernetes-configmap
  namespace: default
  labels:
    app: scdf-server
data:
  application.yaml: |-
    pkslow:
      age: 19
      email: [email protected]
      webSite: www.pkslow.com

要注意的是,這裡的名字與前面配置的是一致的,都是spring-cloud-kubernetes-configmap

接著完成DockerfileK8s部署文件就可以了。注意要將Secret的值映射到環境變數:

env:
	- name: PKSLOW_PASSWORD
		valueFrom:
			secretKeyRef:
				name: spring-cloud-kubernetes-secret
				key: pkslow.password

2.2 啟動與測試

應用會在啟動時就去Kubernetes找相應的ConfigMapSecret

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.5.RELEASE)

2020-08-25 00:13:17.374  INFO 7 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='composite-configmap', propertySources=[ConfigMapPropertySource {name='configmap.spring-cloud-kubernetes-configmap.default'}]}
2020-08-25 00:13:17.376  INFO 7 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='composite-secrets', propertySources=[]}

訪問spring-cloud-kubernetes-configmap.localhost/pkslow,可以正確讀取配置,ConfigMapSecret的內容都獲取到了:

3 自動刷新配置

3.1 原理介紹與程式碼變更

我們需要在Web運行過程中修改配置並使配置生效,有多種模式。修改配置文件如下:

server:
  port: 8080
spring:
  application:
    name: spring-cloud-kubernetes-configmap
  cloud:
    kubernetes:
      config:
        name: spring-cloud-kubernetes-configmap
        namespace: default
      secrets:
        name: spring-cloud-kubernetes-secret
        namespace: default
        enabled: true
      reload:
        enabled: true
        monitoring-config-maps: true
        monitoring-secrets: true
        strategy: restart_context
        mode: event
management:
  endpoint:
    restart:
      enabled: true
  endpoints:
    web:
      exposure:
        include: restart

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

(2) 載入策略strategy

  • refresh:只對特定的配置生效,有註解@ConfigurationProperties@RefreshScope
  • restart_context:整個Spring Context會優雅重啟,裡面的所有配置都會重新載入。

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

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

(3)模式mode

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

3.2 測試

我們修改一下ConfigMap的配置,並更新到K8s

$ kubectl apply -f src/main/k8s/config.yaml 
configmap/spring-cloud-kubernetes-configmap configured

查看發現ageemail都修改了:

我們查看一下Pod的日誌如下:

Springboot先是檢測到了ConfigMap有了變更,然後觸發Context重啟。

4 總結

Spring Cloud Kubernetes為我們提供了不少Spring Cloud整合Kubernetes的特性,可以引入使用。


配置相關文章:
Springboot整合Spring Cloud Kubernetes讀取ConfigMap,支援自動刷新配置

Spring Cloud Config在Spring Cloud Task中的應用,比Web應用更簡單

Spring Cloud Config整合Spring Cloud Kubernetes,在k8s上管理配置

使用Spring Cloud Config統一管理配置,別再到處放配置文件了

Java怎麼從這四個位置讀取配置文件Properties(普通文件系統-classpath-jar-URL)

註解@ConfigurationProperties讓配置整齊而簡單

只想用一篇文章記錄@Value的使用,不想再找其它了

Springboot整合Jasypt,讓配置資訊安全最優雅方便的方式


歡迎關注微信公眾號<南瓜慢說>,將持續為你更新…

多讀書,多分享;多寫作,多整理。

Tags: