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();
}
}

}

欢迎访问我们的技术交流群425783133

你可能感兴趣的:(mongo)