如何在 Java 代码中使用 SAP 云平台 CloudFoundry 环境的环境变量

本文使用的例子源代码在我的github上。
在我的公众号文章在SAP云平台的CloudFoundry环境下消费ABAP On-Premise OData服务介绍了如何通过 Cloud Connector 连接 ABAP On-Premise 系统。

我创建了三个 service 的实例,详情如上图和下表:

这三个服务实例的名称维护在应用的 manifest.xml 中。
将应用使用 cf push 部署到 CloudFoundry 之后,在 Cockpit 里能观察到生成的系统变量 VCAP_SERVICES:

在 Java 代码里,使用如下代码将该环境变量的值读取出来存储到字符串中。
该 Json 对象的具体字段通过 getJSONObject 读取出来。

下图是 connectivity 实例的 credentials 明细:

1. Octotree
默认的 github 网页里的代码显示没有我们在 IDE 里看到的直观,即代码文件所在的文件夹无法以树形层级结构显示在屏幕左边。

安装 Octotree 之后:

方便多了。

2. Isometric Contributions
github commit 的统计页面比较平淡:

安装了 Isometric Contributions 之后,这个统计页面会以柱状图显示出来,有趣多了:

CloudFoundry 应用的 manifest.xml 里的 env 区域,允许用户自定义变量,如下图 5 个变量所示。

使用 cf push 部署到 CloudFoundry 之后,在 SAP Cloud Platform Cockpit 的 User-Provided Variables 标签页里能看到这 5 个用户自定义的变量。通过点击“Add Varible”按钮能在 Cockpit 里直接添加新的环境变量。下图我添加了一个新的环境变量,名称为 employee_id, 值为 i042416。

在 Java 代码里读取环境变量的方式:
在 Kibana 里观察到运行时 JAVA_OPTS 输出的值:
"msg": "Baal user provided variable: -agentpath:/home/vcap/app/.java-buildpack/open_jdk_jre/bin/jvmkill-1.13.0_RELEASE=printHeapHistogram=1 -Djava.io.tmpdir=/home/vcap/tmp -Djava.ext.dirs=/home/vcap/app/.java-buildpack/container_security_provider:/home/vcap/app/.java-buildpack/open_jdk_jre/lib/ext -Djava.security.properties=/home/vcap/app/.java-buildpack/java_security/java.security -Xss349k -Daccess.logging.enabled=false -Dhttp.port=8080 -Xmx71722K -XX:ReservedCodeCacheSize=240M -XX:MaxDirectMemorySize=10M -XX:MaxMetaspaceSize=109315K -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027",

employee_id 的输出:

版权声明: 本文为 InfoQ 作者【Jerry Wang】的原创文章。
原文链接:【http://xie.infoq.cn/article/8341427ad33ca747cb83b3682】。文章转载请联系作者。
评论