简体   繁体   中英

How to add more than one host in MongoDB connection URI in java

I am adding multiple host in MongoDb connection URI in java .It is working fine if all the host are up and running, But it is giving exception when any of the host in the URI is not responding.

I want if in any case my Primary mongo server goes down then already configured secondary mongo come into action and connection should not break in any case.

mongoURI = mongodb://user name:password@first-host:port,second-host:port/db

Here second host in not working.

Code:

MongoClient mongo = new MongoClient(new MongoClientURI(mongoURI));

Exception: ERROR : Mongo Connection java.net.UnknownHostException .

I assume these hosts are replica sets. Then you can do

MongoClient mongoClient = new MongoClient(Arrays.asList(
   new ServerAddress("localhost", 27017),
   new ServerAddress("localhost", 27018),
   new ServerAddress("localhost", 27019)));

Check the doc if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM