前言
上文讲了关于在kubernetes下如何服务发现和负载均衡,本文将通过例子介绍在kubernetes下的configmap如何在springboot项目中使用
1.项目搭建
- 依赖:这里其实引入
spring-cloud-starter-kubernetes-configmap
就够了implementation 'org.springframework.cloud:spring-cloud-starter-kubernetes-all:1.1.2.RELEASE'
- 配置: ``` server: port: 30000 spring: application: name: service-provider cloud: kubernetes: reload: enabled: true mode: event strategy: shutdown config: enableApi: true enabled: true sources: - name: ${spring.application.name} namespace: ${spring.profiles.active}
logging: level: org.springframework.cloud.gateway: debug org.springframework.cloud.loadbalancer: debug
- 接口:
@Value(“${test}:defualt”) private String value; @SneakyThrows @GetMapping(“/provider-hello”) public String sayHello(HttpServletRequest request){
System.out.println("======收到服务调用请求=====");
return String.format("config-value: %s\n--------------%s!", value,"hello world");
} ``` - 编译、打包 ``` ./gradlew build
docker build -t service-proivder:1.0 .
## 2、配置configmap
- 创建configmap
kubectl create configmap service-privider
- 配置一个自定义变量在configmap内
kind: ConfigMap apiVersion: v1 metadata: name: service-provider namespace: default uid: 3f218bdb-4ba6-41fc-adcf-54148b5b0c71 resourceVersion: ‘119857’ creationTimestamp: ‘2021-12-06T13:43:42Z’ data: application-dev.yml: ‘test: 222222222’
- 查看下当前的配置文件
kubectl describe configmaps service-provider ```
3、测试
- 访问接口
4、结果
访问成功!
- 大致原理:
-
Spring Kubernetes Config 通过指定读取当前服务名一致的configmap,将data下的值通过key:value的形式塞到profile里面去,就能被访问了
-