MongoDB3.0连接

来源:互联网 发布:比基尼激光脱毛知乎 编辑:程序博客网 时间:2024/06/05 00:52
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);    }}
0 0