package com.xunying.util; import com.mongodb.*; import com.xunying.cache.Constant; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class MongoPool { //数据库链接池 private static MongoClient client = null; //日志 private static final Logger log = Logger.getLogger(MongoPool.class); static { getClient(); } /** * 创建数据库连接池 */ private static void getClient(){ //配置链接地址,端口 ServerAddress address = null; try { address = new ServerAddress("192.168.2.102", 27017); } catch (Exception e) { log.error("链接数据库异常,请查看数据库是否关闭 ------>" + e.getMessage()); return; } //启用身份验证 boolean needPassword = true; if(needPassword) { //配置访问权限验证 MongoCredential credential = MongoCredential.createMongoCRCredential( "root",//用户名 "adminDb", //数据库名 "passwords".toCharArray()); //密码,是字符的数组 //设置为1,避免浪费资源(因为只有一个参数对象) List<MongoCredential> list = new ArrayList<MongoCredential>(1); list.add(credential); client = new MongoClient(address, list); }else{ client = new MongoClient(address); } /* *连接池设置 */ MongoClientOptions mongoClientOptions = client.getMongoClientOptions(); MongoClientOptions.Builder builder = mongoClientOptions.builder(); builder.connectionsPerHost(10); builder.threadsAllowedToBlockForConnectionMultiplier(10); } /** * 创建数据库链接 * @param dbName 数据库名称 * @return 链接对象 */ public static DB getDataBase(String dbName){ return client.getDB(dbName); } /** * 创建数据表链接 * @param dbName 数据库名称 * @param collectionName 数据表名 * @return 数据链接对象 */ public static DBCollection getCollection(String dbName, String collectionName){ return client.getDB(dbName).getCollection(collectionName); } }
MongoDB3.0连接
最新推荐文章于 2021-11-17 09:26:37 发布