Mongo3.4.2用户连接认证

三、mongodb3.4使用随笔


The MongoClient instance represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

这句话的意思其实就是说我们的mongo是自带数据库连接池的,不需要我们像使用关系型数据库那样要配置数据库连接池,直接拿来就可以用。

mongo从3.0开始认证机制跟之前的版本认证机制不同。

代码如下:

/**
*  
* @param username 用户名
* @param pwd 密码
* @param dbName 数据库名称
* @return
*/
public static MongoDatabase getDataBase(String username, String pwd, String dbName){
MongoCredential credential = MongoCredential.createCredential(username, dbName, pwd.toCharArray());
MongoClient client = new MongoClient(new ServerAddress("127.0.0.1"), Arrays.asList(credential));
MongoDatabase db = client.getDatabase(dbName);
return db;
}
/**

* @param collectionName
* @return 获取collection对象
*/
public static MongoCollection<Document> getCollection(String collectionName){
MongoDatabase db = getDataBase("test", "123456", "test");
MongoCollection<Document> collection = db.getCollection(collectionName);
return collection;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值