想了半天如何解决mongodb复制集master出问题,程序如何自动连接到slave(当然这里冲裁选举完毕),朋友说java代码可以实现,
找到如下代码:
http://api.mongodb.org/java/3.0/com/mongodb/MongoClient.html
com.mongodb
Class MongoClient
java.lang.Object
com.mongodb.Mongo
com.mongodb.MongoClient
All Implemented Interfaces:
Closeable, AutoCloseable
public class MongoClient
extends Mongo
implements Closeable
A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.
The following are equivalent, and all connect to the local database running on the default port:
MongoClient mongoClient1 = new MongoClient();
MongoClient mongoClient1 = new MongoClient("localhost");
MongoClient mongoClient2 = new MongoClient("localhost", 27017);
MongoClient mongoClient4 = new MongoClient(new ServerAddress("localhost"));
MongoClient mongoClient5 = new MongoClient(new ServerAddress("localhost"), new MongoClientOptions.Builder().build());
You can connect to a replica set using the Java driver by passing a ServerAddress list to the MongoClient constructor. For example:
MongoClient mongoClient = new MongoClient(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. MongoClient 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:
mongoClient.setReadPreference(ReadPreference.secondaryPreferred());
By default, all write operations will wait for acknowledgment by the server, as the default write concern is WriteConcern.ACKNOWLEDGED.
Note: This class supersedes the Mongo class. While it extends Mongo, it differs from it in that the default write concern is to wait for acknowledgment from the server of all write operations. In addition, its constructors accept instances of MongoClientOptions and MongoClientURI, which both also set the same default write concern.
In general, users of this class will pick up all of the default options specified in MongoClientOptions. In particular, note that the default value of the connectionsPerHost option has been increased to 100 from the old default value of 10 used by the superseded Mongo class.
Since:
2.10.0
See Also:
ReadPreference.primary(), WriteConcern.ACKNOWLEDGED, MongoClientOptions, MongoClientURI
Nested Class Summary
Nested classes/interfaces inherited from class?com.mongodb.Mongo
Mongo.Holder
各位朋友给我看看是否可以实现。我不会写java