最近使用Appfog开发一些Web应用,但在部署应用时,遇到问题----应用不能正常连接Appfog提供的数据库服务,原因在于Appfog并没有在其提供的控制面板中,提供的数据库连接的具体参数信息......不过后来在Appfog的Doc中,找到了相关的解决方法:
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:
{"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所描述的。
不同的编程语言访问的方式如下:
Java:
java.lang.System.getenv("VCAP_SERVICES")
JavaScript:
process.env.VCAP_SERVICES
Python:
os.getenv("VCAP_SERVICES")
PHP:
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提供服务。
本文由zhiweiofli编辑发布,转载请注明出处,谢谢。