通過 VCAP SERVICES 環境變數訪問憑據

將服務繫結到應用程式憑據時,可通過 VCAP_SERVICES 環境變數獲取憑據。

此環境變數包含 JSON,其中包含所有繫結服務的憑據。

示例 VCAP_SERVICES 環境變數

{
   "push-reappt": [
      {
         "name": "Reappt from Push Technology",
         "label": "push_reappt",
         "plan": "reappt:pushtechnology:free",
         "credentials": {
            "principal": "service-binding-abcd1234",
            "credentials": "XYZlmnop456",
            "host": "sniffingitchyPythagoras.eu.bluemix.reappt.io",
            "port": 443
         }
      }
   ]
}

然後,你可以通過應用程式訪問這些憑據。

使用 Javascript

在 Node 應用程式中,你可以執行以下操作:

var reappt_credentials = JSON.parse(process.env.VCAP_SERVICES)["push-reappt"][0].credentials;

diffusion.connect({
    host : reappt_credentials.host,
    principal : reappt_credentials.principal,
    credentials : reappt_credentials.credentials
}).then(connected, error);

Java

在 Java 應用程式中,可以按如下方式完成相同的操作:

    private static final JsonParser PARSER = new JsonParser();
    private static final JsonObject VCAP_SERVICES = PARSER.parse(System.getenv("VCAP_SERVICES")).getAsJsonObject();

    private static final JsonObject REAPPT_CREDENTIALS = VCAP_SERVICES.getAsJsonArray("push-reappt").get(0)
                .getAsJsonObject().getAsJsonObject("credentials");
    protected static final String HOST = REAPPT_CREDENTIALS.getAsJsonPrimitive("host").getAsString();
    protected static final String PRINCIPAL = REAPPT_CREDENTIALS.getAsJsonPrimitive("principal").getAsString();
    protected static final String CREDENTIALS = REAPPT_CREDENTIALS.getAsJsonPrimitive("credentials").getAsString();