通过 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();