Mongo mongo = new Mongo(Arrays.asList( new ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018), new ServerAddress("localhost", 27019)));You can connect to a sharded cluster using the same constructor. Mongo will auto-detect whether the servers are a list of replica set members or a list of mongos servers.
By default, all read and write operations will be made on the primary, but it's possible to read from secondaries by changing the read preference:
mongo.setReadPreference(ReadPreference.secondary());By default, write operations will not throw exceptions on failure, but that is easily changed too:
mongo.setWriteConcern(WriteConcern.SAFE);Note: This class has been superseded by {@code MongoClient}, and may be deprecated in a future release. @see MongoClient @see ReadPreference @see WriteConcern
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.
You can connect to a replica set using the Java driver by passing several a list if ServerAddress to the Mongo constructor. For example:
Listaddrs = 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();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|