Springboot整合Spring Cloud Kubernetes讀取ConfigMap,支援自動刷新配置
1 前言
歡迎訪問南瓜慢說 www.pkslow.com獲取更多精彩文章!
Docker & Kubernetes相關文章:
容器技術
之前介紹了Spring Cloud Config
的用法,但對於Kubernetes
應用,可能會需要讀取ConfigMap
的配置,我們看看Springboot
是如何方便地讀取ConfigMap
和Secret
。
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 Web
和Spring 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
。
接著完成Dockerfile
和K8s
部署文件就可以了。注意要將Secret
的值映射到環境變數:
env:
- name: PKSLOW_PASSWORD
valueFrom:
secretKeyRef:
name: spring-cloud-kubernetes-secret
key: pkslow.password
2.2 啟動與測試
應用會在啟動時就去Kubernetes
找相應的ConfigMap
和Secret
:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: 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
,可以正確讀取配置,ConfigMap
和Secret
的內容都獲取到了:
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
查看發現age
和email
都修改了:
我們查看一下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讓配置整齊而簡單
Springboot整合Jasypt,讓配置資訊安全最優雅方便的方式
歡迎關注微信公眾號<南瓜慢說>,將持續為你更新…
多讀書,多分享;多寫作,多整理。