0

我们正在努力将一个 Java 项目部署到使用 MongoDB 的 Heroku。根据Heroku 文档,数据库连接参数是从环境变量中读取的,MONGOHQ_URL. 当我在笔记本电脑上运行 Netbeans 项目时,如何设置此变量?

-DMONGOHQ_URL=...我尝试在 Run -> Set Project Configuration -> Customize -> Run 以及 Actions -> Run project and Run file via main()中将其添加为 VM 选项,但无济于事。当程序System.getvar在未设置的情况下读取它时。

4

2 回答 2

0

您可以在netbeans.conf文件中设置它。添加行:

export MONGOHQ_URL=...

这里有一个例子:http: //sunng.info/blog/2009/12/setting-environment-variables-for-netbeans/

于 2012-04-17T18:30:20.757 回答
0

好的,我想通了。这对 Java 编码人员来说可能很明显,但我不是其中之一,所以这是我拼凑起来的。

    String mongo_url = System.getenv("MONGOHQ_URL");
    // If env var not set, try reading from Java "system properties"
    if (mongo_url == null) {
        mongo_url = System.getProperty("MONGOHQ_URL");
    }

    MongoURI mongoURI = new MongoURI(mongo_url);
    this.db = mongoURI.connectDB();

    // Only authenticate if username or password provided
    if (!"".equals(mongoURI.getUsername()) || mongoURI.getPassword().length > 0) {
        Boolean success = this.db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());  

        if (!success) {
            System.out.println("MongoDB Authentication failed");
            return;
        }
    }
    this.my_collection = db.getCollection("my_collection");
于 2012-04-17T19:11:56.867 回答