ongodb.org/display/DOCS/Java+Driver+Concurrency
Connecting to a Replica Pair
You can connect to a replica pair using the Java driver by passing two DBAddresses to the Mongo constructor. For example:
DBAddress left = new DBAddress("127.0.0.1:27017/test"); DBAddress right = new DBAddress("127.0.0.1:27018/test"); Mongo mongo = new Mongo(left, right);
If the master of a replica pair goes down, there will be a brief lag before the slave becomes master. Thus, your application should be prepared to catch the exceptions that might be thrown in such a case: IllegalArgumentException, MongoException, and MongoException.Network (depending on when the connection drops).
Once the slave becomes master, the driver will begin using that connection as the master connection and the exceptions will stop being thrown.
Connecting to a Replica Set
You can connect to a replica set using the Java driver by passing several a list if ServerAddress to the Mongo constructor. For example:
List addrs = new ArrayList(); addrs.add( new ServerAddress( "127.0.0.1" , 27017 ) ); addrs.add( new ServerAddress( "127.0.0.1" , 27018 ) ); addrs.add( new ServerAddress( "127.0.0.1" , 27019 ) ); Mongo mongo = new Mongo( addrs );
By default, all read and write operations will be made on the master. But it's possible to read from the slave(s) by using slaveOk:
mongo.slaveOk();