import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import java.util.Arrays; /**
* @作者 yan
* @创建日期 2017-3-16 14:42:20
* @版本 V1.0
* @描述 MongoDB JDBC工具类
*/
public class MongodbUtil { private static MongoClient mongoClient = null; private MongodbUtil() {} static {
if(PropertiesUtil.getInt("mongodb.auth")==1){
initAuthDB();
}else{
initDB();
}
} public static MongoDatabase getDB() {
if (null != mongoClient) {
setOptions(); return mongoClient.getDatabase(PropertiesUtil.getString("mongodb.dbname"));
} return null;
} /**
* 无认证链接
*/
private static void initDB() {
MongoClientURI uri = new MongoClientURI(
PropertiesUtil.getString("mongodb.uri"),
MongoClientOptions.builder().cursorFinalizerEnabled(false)); mongoClient = new MongoClient(uri);
} /**
* 认证链接
*/
private static void initAuthDB(){
MongoCredential credential = MongoCredential.createCredential(
PropertiesUtil.getString("mongodb.user"),
PropertiesUtil.getString("mongodb.dbname"),
PropertiesUtil.getString("mongodb.pwd").toCharArray()); ServerAddress addr = new ServerAddress(
PropertiesUtil.getString("mongodb.host"),
PropertiesUtil.getInt("mongodb.port")); mongoClient = new MongoClient(addr,Arrays.asList(credential));
} /**
* 连接池配置
*/
private static void setOptions(){
MongoOptions opt = mongoClient.getMongoOptions();
opt.connectionsPerHost = PropertiesUtil.getInt("mongodb.poolsize");
opt.threadsAllowedToBlockForConnectionMultiplier = PropertiesUtil.getInt("mongodb.blocksize");
}
}
05-12 04:21