mongo-java-driver連線mongo叢集
此處mongo-java-driver版本為2.13
import java.net.UnknownHostException;
import java.util.Arrays;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
public class MongoConnFactory {
private static MongoClient mongoClient = null;
public static DB getDB() throws UnknownHostException {
DB conn = null;
if(mongoClient == null){
intializeMongoClient();
}
String dbName = "yourdbname";
conn = mongoClient.getDB(dbName);
conn.authenticate("loginName", "password".toCharArray());
conn.slaveOk();
return conn;
}
private static void intializeMongoClient() throws UnknownHostException {
mongoClient = new MongoClient(Arrays.asList(new ServerAddress("10.111.129.11", 8021),
new ServerAddress("10.111.129.12", 8021),
new ServerAddress("10.111.129.13", 8021)));
}
public static synchronized void closeConnection(){
if(mongoClient != null){
mongoClient.close();
}
}
}