如何得到Appfog,Cloundfoundry提供的云数据库信息

      最近使用Appfog开发一些Web应用,但在部署应用时,遇到问题----应用不能正常链接Appfog提供的数据库服务,缘由在于Appfog并无在其提供的控制面板中,提供的数据库链接的具体参数信息......不事后来在AppfogDoc中,找到了相关的解决方法: php

When you provision and bind a service to your app, AppFog creates an environment variable called VCAP_SERVICES. This variable contains a JSON document with a list of all credentials and connection information for the bound services. Here's an example that of the environment variable for an app that has two MySQL database services bound to it: java


{"mysql-5.1":[
    {
        "name":"mysql-4f700",
        "label":"mysql-5.1",
        "plan":"free",
        "tags":["mysql","mysql-5.1","relational"],
        "credentials":{
            "name":"d6d665aa69817406d8901cd145e05e3c6",
            "hostname":"mysql-node01.us-east-1.aws.af.cm",
            "host":"mysql-node01.us-east-1.aws.af.cm",
            "port":3306,
            "user":"uB7CoL4Hxv9Ny",
            "username":"uB7CoL4Hxv9Ny",
            "password":"pzAx0iaOp2yKB"
        }
    },
    {
        "name":"mysql-f1a13",
        "label":"mysql-5.1",
        "plan":"free",
        "tags":["mysql","mysql-5.1","relational"],
        "credentials":{
            "name":"db777ab9da32047d99dd6cdae3aafebda",
            "hostname":"mysql-node01.us-east-1.aws.af.cm",
            "host":"mysql-node01.us-east-1.aws.af.cm",
            "port":3306,
            "user":"uJHApvZF6JBqT",
            "username":"uJHApvZF6JBqT",
            "password":"p146KmfkqGYmi"
        }
    }
]}


      根据文档所说,在Appfog提供的控件部署的应用都可经过访问一个环境变量 VCAP_SERVICES 来得到链接的数据库服务的具体信息,如上面的Json所描述的。 node

      不一样的编程语言访问的方式以下: mysql

      Java: sql

java.lang.System.getenv("VCAP_SERVICES")

      JavaScript: 数据库

process.env.VCAP_SERVICES

      Python: 编程

os.getenv("VCAP_SERVICES")

      PHP: json

getenv("VCAP_SERVICES")

     以PHP为例: 架构

<?php  
      $services_json = json_decode(getenv("VCAP_SERVICES"),true);   //进行得到数据库信息的json文件解析  
      $mysql_config = $services_json["mysql-5.1"][0]["credentials"];  
      $username = $mysql_config["username"];  
      $password = $mysql_config["password"];  
      $hostname = $mysql_config["hostname"];  
      $port = $mysql_config["port"];  
      $db = $mysql_config["name"];  
        
 ?>

       将上面的代码写进应用的配置文件,upload并运行,便可在运行时得到该应用所绑定的数据库服务的链接信息!因为Appfog使用了Cloundfoundry的开源架构,故此方法也适用于Cloundfoundry提供服务。 app


      本文由zhiweiofli编辑发布,转载请注明出处,谢谢。

相关文章
相关标签/搜索