我使用以下代码来读取Liberty应用程序的VCAP_SERVICES
环境变量。
我没有得到任何值,结果显示为null或"未找到"。
private void readECaaSEnvVars() {
Map<?, ?> env = System.getenv();
Object vcap = env.get("VCAP_SERVICES");
if (vcap == null) {
System.out.println("No VCAP_SERVICES found");
}
else {
try {
JSONObject obj = new JSONObject(vcap);
String[] names = JSONObject.getNames(obj);
if (names != null) {
for (String name : names) {
if (name.startsWith("DataCache")) {
JSONArray val = obj.getJSONArray(name);
JSONObject serviceAttr = val.getJSONObject(0);
JSONObject credentials = serviceAttr.getJSONObject("credentials");
String username = credentials.getString("username");
String password = credentials.getString("password");
String endpoint=credentials.getString("catalogEndPoint");
String gridName= credentials.getString("gridName");
System.out.println("Found configured username: " + username);
System.out.println("Found configured password: " + password);
System.out.println("Found configured endpoint: " + endpoint);
System.out.println("Found configured gridname: " + gridName);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
您的解析代码没问题。
cf restage <appname>
System.out.println("VCAP_SERVICES: " + System.getenv("VCAP_SERVICES"));
您还应该知道,默认情况下,Liberty buildpack会为数据缓存实例生成或更新现有的server.xml文件配置节。应用程序可以使用JNDI访问绑定的数据高速缓存实例。缓存实例可以使用@Resource注释注入应用程序,也可以由应用程序使用javax.naming.InitialContext进行查找。
要在Bluemix for Liberty应用程序上查看server.xml:
cf files myLibertyApplication app/wlp/usr/servers/defaultServer/server.xml
您应该看到类似的内容:
<xsBindings>
<xsGrid jndiName="wxs/myCache"
id="myCache"
gridName="${cloud.services.myCache.connection.gridName}"
userName="${cloud.services.myCache.connection.username}"
password="${cloud.services.myCache.connection.password}"
clientDomain="${cloud.services.myCache.name}"/>
</xsBindings>
您的JNDI名称是wxs / myCache。这样就无需解析VCAP_SERVICES。