如何在AppFog/CloudFoundry上使用MongoDB部署Grails



Grails在本地与mongodb插件配合得很好,但我在AppFog上遇到了问题。

在AppFog上部署Grails的说明对于MongoDB以外的数据库来说相当清晰。该文档似乎暗示了MongoDB的自动配置,但是如果我将配置设置为以下内容,则不起作用。

//DataSource.groovy
grails {
  mongo {
    host = "localhost"
    port = 27017
    databaseName = "dbname"
  }
}

自动配置似乎不会将本地主机替换为正确的主机名。似乎我需要从VCAP_SERVICES中设置值。

你的Grails项目中是否安装了CloudFoundry插件?该插件在Grails应用程序中对MongoDB和其他数据源进行自动重新配置。

如果由于某种原因你不能或不想使用Grails CloudFoundry插件,那么使用上面显示的环境变量的另一种选择是使用cloudfoundry-runtime Java API。此 API 允许您访问存储在环境变量中的相同信息,但它比直接解析环境变量要干净一些。

联系支持人员后,答案是使用 VCAP_SERVICE 环境变量。在网上挖掘后,我想出了如何在配置中检索和使用VCAP_SERVICES。

grails {
    def vcap = System.env.VCAP_SERVICES
    def credentials = vcap ? grails.converters.JSON.parse(vcap)["mongodb-1.8"][0]["credentials"] : null
    mongo {
        host = credentials ? credentials.hostname : "localhost"
        port = credentials ? credentials.port : "27017"
        username = credentials ? credentials.username : null
        password = credentials ? credentials.password : null
        databaseName = credentials ? credentials.db : "dbname"
    }
}

我还创建了一个 github gist 这个配置。

最新更新