【问题标题】:Consuming kubernetes configmap in springboot application在 Spring Boot 应用程序中使用 kubernetes configmap
【发布时间】:2021-10-24 21:19:56
【问题描述】:

我是 kubernetes 新手,需要在 openshift 平台上使用 k8s configmap 将 springboot 应用程序的属性文件外部化。我已将属性文件保存在 git repo 中 “greeter.message=Spring Boot myapplication.properties 已作为卷挂载在 Kubernetes 上!” 并使用 "oc create configmap myconfig --from-file=myapplication.properties" 命令创建了配置映射。 我也可以使用 "oc get configmap myconfig -o yaml" 命令看到同样的结果:

data:
  myapplication.properties: greeter.message=Spring Boot myapplication.properties has been mounted as volume on Kubernetes!
    on Kubernetes!
kind: ConfigMap
metadata:
  creationTimestamp: 2021-08-24T04:45:27Z
  name: myconfig 
  namespace: mynamespace
  resourceVersion: "53471"
  selfLink: /api/v1/namespaces/default/configmaps/myconfig
  uid: 73ca674c-8afc-71e1-9a8a-7da609902085

现在我有一个 springboot 休息控制器

 @RestController
@Slf4j
public class GreeterController {

    @Value("${greeter.message}")
    private String greeterMessageFormat; 

    @GetMapping("/greet/{user}")
    public String greet(@PathVariable("user") String user) {
        return String.format(greeterMessageFormat);
    }
}

最后,我对部署文件进行了更改,以创建卷并将其挂载为

spec:
      containers:
          volumeMounts:
          - name: application-config 
            mountPath: "/etc/config" 
            readOnly: true
      volumes:
      - name: application-config
        configMap:
          name: myconfig

现在当我尝试启动 pod 时出现问题,springboot 应用程序无法启动,表明它在 @Value("${greeter.message}") 中找不到 ${greeter.message} 的任何值我在应用程序 src/main/resources/app.properties 中没有任何此类属性,如果我提供了一个,那么我的 springboot 应用程序会从 src/main/resources/app.properties 而不是 configmap 中选择该属性。

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'greeter.message' in value "${greeter.message}"

预计该值应取自我创建的配置映射。 请帮我解决我遗漏的地方。

我已经提到了这个 https://developers.redhat.com/blog/2017/10/03/configuring-spring-boot-kubernetes-configmap#cm-as-files 并做了同样的事情。

提前致谢。

【问题讨论】:

标签: java spring-boot kubernetes properties-file configmap


【解决方案1】:

试试

   envFrom:                ##Reference all key-value pairs of the sepcial-config ConfigMap. 
   - configMapRef:
       name: myconfig

参考资料:

https://www.exoscale.com/syslog/configuration-management-kubernetes-spring-boot/ https://www.alibabacloud.com/help/doc-detail/86556.htm

【讨论】:

  • 嗨@Rakesh,谢谢您的回复。您建议的方式工作正常,但不需要创建和安装卷。那只是使用 Env 变量中的 configmap 值。我想做的是创建卷并在我的springboot应用程序中使用它。你能帮帮我吗?
  • 您也可以将配置挂载为文件,但是,您需要告诉 spring 读取该特定文件。您可以将其安装在默认位置或按照@Tomasz 在他的评论中的建议设置属性 spring.config.location
猜你喜欢
  • 2020-03-29
  • 2022-01-12
  • 2022-01-11
  • 2018-09-07
  • 1970-01-01
  • 2019-07-20
  • 2021-11-30
  • 2020-05-06
  • 1970-01-01
相关资源
最近更新 更多