Mongo3.4.2用户连接认证

来源:互联网 发布:淘宝心愿单是什么 编辑:程序博客网 时间:2024/05/21 15:07

三、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;
}

原创粉丝点击