1

我在 Bluemix 上有两个应用程序,我需要将一个应用程序的 URL 提供给另一个应用程序。

$response = http_get("myOrdersApp12345.mybluemix.net/api");

在我的源代码中对 URL 进行硬编码似乎是个坏主意……如果 url 发生变化怎么办?

4

2 回答 2

4

硬编码 URL 或源中的任何凭据是不好的做法。在 Bluemix 中,您可以使用 VCAP_SERVICES 环境变量将这些凭证传递给您的应用程序。这是保存 Bluemix 服务凭证的同一个环境变量。

您实际上是通过创建用户提供的服务来创建对您的组织和空间可见的自己的服务

创建一个新服务,向该服务的消费者提供 url:

$ cf cups myOrdersAppService -p "url"
url> myOrdersApp12345.mybluemix.net/api
Creating user provided service myOrdersApp in org **** / space ****
OK

然后将此服务绑定到需要此“url”信息的应用程序

$ cf bind-service myOtherApplication myOrdersAppService

myOtherApplication 可以通过解析 VCAP_SERVICES 环境变量来获取 url。例如,在 PHP 中:

$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services, true);

for ($i = 0; $i < sizeof($services_json["user-provided"]); $i++){
    if ($services_json["user-provided"][$i]["name"] == "myOrdersApp"){
        $ordersHost = $services_json["user-provided"][$i]["credentials"]["url"];
        $response = http_get($ordersHost);
    }
}

您可以使用相同的方法来共享任何外部服务(如数据库)的凭据。当使用微服务架构时,这个特性变得非常有用。

$ cf cups myExternalDB -p "host, username, password"
host> 123.123.123.123
username> myusername
password> mypassw0rd

有关更多详细信息,请查看此文档:http ://docs.cloudfoundry.org/devguide/services/user-provided.html

于 2015-04-23T18:36:15.593 回答
2

我同意 Ram 的建议,即通过 检索服务参数VCAP_SERVICES,特别是当它指定服务绑定到您的应用程序(如凭据)的内在信息时。但是,对于更普通的配置属性(例如,支持哪些语言以及翻译位于何处?应该使用哪个 URL 来调用此 REST 服务?),传统方法如在命令行中传递它们,从配置文件中检索它们,或者从管理员在部署时指定的环境变量中获取它们是完全合法的。

Pat Mueller's Keeping secrets – how your cloud application should access credentials and other private data nicely summarizes the options and tradeoffs. Most importantly, he underscores the importance of not hardcoding sensitive information, especially given the likelihood that code will be stored in a repository where it's not readily evident who will have access, unlike a deployment script maintained by the system admin.

于 2015-04-23T20:46:36.237 回答