如何得到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編輯發佈,轉載請註明出處,謝謝。

相關文章
相關標籤/搜索