java - 使用 configMap 和 Volumes 从 kubernetes 读取配置文件

标签 java kubernetes openshift

所以我正在努力从 kubernetes 读取 xml 文件。我正在运行一个开放的自由服务器和一个 Maven 打包的 war 应用程序。我需要对 Java 代码进行哪些更改才能从 kubernetes 读取文件。

这里的问题是代码从 war 文件内的资源文件夹中读取 pdp.xml,而不是从外部的 kubernetes 卷中读取。

我的 configMap 看起来像这样

kind: ConfigMap
apiVersion: v1
metadata:
  name: testing-config
data:
  pdp.xml: |
   <pdp    xmlns="http://authzforce.github.io/core/xmlns/pdp/7"
           xmlns:att="za.co.some.data"
           xmlns:xacml="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
           version="7.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   </pdp>

这是带有卷的 yaml 文件

apiVersion: apps/v1
kind: Deployment
metadata:
  name: testing-app
  labels:
    app: testing-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: testing-app
  template:
    metadata:
      labels:
        app: testing-app
    spec:
      containers:
      - name: testing-app
        image: testing-app:1.0.24-SNAPSHOT
        imagePullPolicy: Always
        volumeMounts:
        - name: testing-app-volume
          mountPath: /config/pdp.xml
          subPath: pdp.xml
          readOnly: true
      volumes:
      - name: testing-app-volume
        configMap:
          name: testing-app-config
      restartPolicy: Always

我不太了解 Java,但这是我读取文件的方式。

Resource resource = new ClassPathResource("pdp.xml");
InputStream cfgFile = null;
byte[] buffer = null;
try {
  cfgFile = resource.getInputStream();
  buffer = new byte[cfgFile.available()];
} catch (IOException e) {
  log.error(ERROR_MESSAGE);
  throw new IllegalStateException(ERROR_MESSAGE);
}

这是容器内的文件夹结构

enter image description here

最佳答案

非常简单。只需从安装文件的同一位置读取该文件即可:/config/pdp.xml

所以,在你的代码中:

Resource resource = new ClassPathResource("/config/pdp.xml");
InputStream cfgFile = null;
byte[] buffer = null;
try {
  cfgFile = resource.getInputStream();
  buffer = new byte[cfgFile.available()];
} catch (IOException e) {
  log.error(ERROR_MESSAGE);
  throw new IllegalStateException(ERROR_MESSAGE);
}

...或将其安装到应用程序正在读取的目录: 挂载路径:/liberty/usr/servers/defaultServer/pdp.xml

关于java - 使用 configMap 和 Volumes 从 kubernetes 读取配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61361117/

相关文章:

docker - 在OpenShift上卷而不从空目录开始

java - list 合并失败 : Attribute application@appComponentFactory updating Firebase libraries

java - 需要帮助将编辑文本值与 Android 中自定义 ListView 中的 TextView 值相乘

java - 我应该在编辑 Java 文件的同时只修改 Android 的 XML 吗?

kubernetes - 使用 helm Charts 安装 k8s 后,LoadBalancer 'EXTERNAL IP"处于挂起状态

Azure AKS 群集节点磁盘类型

c# - 通过MySql.Data.MySqlClient方法连接OpenShift云端的MySQL服务器

java - Java 编译器是否包含字符串常量折叠?

kubernetes - 重命名 Kubernetes 中的部署

maven - 如何在 OpenShift3 中通知 S2I 构建的 Maven/JVM 选项