使用属性参数化与Mongodb的连接

时间:2021-12-09 03:13:55

I am trying to use Properties file to parameterize connection to Mongodb.

我正在尝试使用Properties文件来参数化与Mongodb的连接。

I have added this function:

我添加了这个功能:

public static Properties load(String filename) throws IOException, FileNotFoundException{
  Properties properties = new Properties();

  FileInputStream input = new FileInputStream(filename);
  try{
     properties.load(input);
     return properties;
  }
     finally{
     input.close();
  }

}

and use this code:

并使用此代码:

    String path = System.getProperty("user.dir") + "/config.properties";
    Properties prop = load(path);

    //System.out.println("key: "+ prop.getProperty("MONGO_HOST"));


    try {
//m = new Mongo(config.MONGO_HOST, config.MONGO_PORT);
    m = new Mongo(prop.getProperty("MONGO_HOST"), config.MONGO_PORT);
this.db = m.getDB("cloud_datasource");
             db.authenticate(config.MONGO_USER, config.MONGO_PASS.toCharArray());
    } catch (Exception e) {
System.out.println("Can't connect to MongoDB");
             e.printStackTrace();

    }

In my config.properties: MONGO_HOST="192.168.10.84"

在我的config.properties中:MONGO_HOST =“192.168.10.84”

Problem: with this code, I have an error java.net.UnknownHostException: "192.168.10.84" but if I am using the code:

问题:使用此代码,我有一个错误java.net.UnknownHostException:“192.168.10.84”但如果我使用的代码:

m = new Mongo("192.168.10.84", config.MONGO_PORT);

it works.

2 个解决方案

#1


0  

Try this (without quotes):

试试这个(没有引号):

MONGO_HOST=192.168.10.84

#2


0  

make sure what Tomasz said (no double quotes in prop file). then if it still doesn't work then maybe cast the prop.getProperty() to a String like this:

确定Tomasz说的是什么(在prop文件中没有双引号)。然后,如果它仍然无法工作,那么可以将prop.getProperty()强制转换为这样的String:

m = new Mongo((String)prop.getProperty("MONGO_HOST"), config.MONGO_PORT);

#1


0  

Try this (without quotes):

试试这个(没有引号):

MONGO_HOST=192.168.10.84

#2


0  

make sure what Tomasz said (no double quotes in prop file). then if it still doesn't work then maybe cast the prop.getProperty() to a String like this:

确定Tomasz说的是什么(在prop文件中没有双引号)。然后,如果它仍然无法工作,那么可以将prop.getProperty()强制转换为这样的String:

m = new Mongo((String)prop.getProperty("MONGO_HOST"), config.MONGO_PORT);