Springboot整合Spring Cloud Kubernetes读取ConfigMap,支持自动刷新配置

Parallel
• 阅读 1588

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: admin@pkslow.com
      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的内容都获取到了:

Springboot整合Spring Cloud Kubernetes读取ConfigMap,支持自动刷新配置

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都修改了:

Springboot整合Spring Cloud Kubernetes读取ConfigMap,支持自动刷新配置

我们查看一下Pod的日志如下:

Springboot整合Spring Cloud Kubernetes读取ConfigMap,支持自动刷新配置

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,让配置信息安全最优雅方便的方式


欢迎关注微信公众号<南瓜慢说>,将持续为你更新...

Springboot整合Spring Cloud Kubernetes读取ConfigMap,支持自动刷新配置

多读书,多分享;多写作,多整理。

点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Wesley13 Wesley13
4年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Stella981 Stella981
4年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
4年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
4年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Easter79 Easter79
4年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Stella981 Stella981
4年前
C++ OpenCV特征提取之AKAZE检测
前言前一章我们介绍过《COpenCV特征提取之KAZE检测(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzA4Nzk0NTU0Nw%3D%3D%26mid%3D2247485573%26idx%3D1
Wesley13 Wesley13
4年前
C++创建动态库C#调用(二)
前言上一篇《C创建动态库C调用(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzA4Nzk0NTU0Nw%3D%3D%26mid%3D2247486189%26idx%3D1%26sn%3D46a4d0
Stella981 Stella981
4年前
Linux日志安全分析技巧
0x00前言我正在整理一个项目,收集和汇总了一些应急响应案例(不断更新中)。GitHub地址:https://github.com/Bypass007/EmergencyResponseNotes本文主要介绍Linux日志分析的技巧,更多详细信息请访问Github地址,欢迎Star。0x01日志简介Lin