无法读取Bluemix中的VCAP_SERVICES

时间:2015-12-11 12:49:39

标签: ibm-cloud websphere-liberty

我使用以下代码来读取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();
           }
         }
        }

1 个答案:

答案 0 :(得分:2)

您的解析代码没问题。

  1. 在您的Bluemix应用程序仪表板中,确认您已将DataCache服务绑定到您的应用程序。
  2. 新服务绑定后,您需要重新启动环境变量的应用程序以进行更新。 cf restage <appname>
  3. 输出环境变量以确认DataCache凭据位于System.out.println("VCAP_SERVICES: " + System.getenv("VCAP_SERVICES"));
  4. 您还应该知道,默认情况下,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。