標籤:
以下操作基於Windows平台
1、啟動MongoDB服務
mongod.exe --dbpath d:\mongodb-win32-x86_64-2.2.2\data --logpath d:\mongodb-win32-x86_64-2.2.2\log\mongo.log --auth
【--auth】:代表需要根據許可權訪問,必須加此參數啟動服務,用戶端才能以使用者名稱密碼方式建立串連
2、啟動Mongo控制台 mongo
- D:\mongodb-win32-x86_64-2.2.2\bin>mongo
- MongoDB shell version: 2.2.2
- connecting to: test
- >
3、切換到要設定的資料庫,建立使用者
- > use caotian
- switched to db caotian
- > db.addUser("ctAdmin","111111");
- {
- "user" : "ctAdmin",
- "readOnly" : false,
- "pwd" : "790457ca1e19341d5043766e9192c5b9",
- "_id" : ObjectId("549943e6cbd0bdf00f57783b")
- }
- >
4、Java中建立串連
- try {
- ServerAddress sa = new ServerAddress("localhost","27017");
- MongoOptions options = new MongoOptions();
- options.connectionsPerHost = 200;//pool size(驅動的連結池大小). /* mongod --dbpath ..\db --maxConns 20(並發數) */ 預設都為10
- this.mongo = new Mongo(sa, options);
- this.db = this.mongo.getDB("caotian");
- char[] pwd_char = "111111".toCharArray();
- boolean auth = db.authenticate("ctAdmin",pwd_char);
- if(!auth){
- logger.info("======MongoDB 初始化許可權驗證錯誤======");
- throw new RuntimeException();
- }
- logger.info("======MongoDB 初始化完成======");
- } catch (UnknownHostException e) {
- e.printStackTrace();
- } catch (MongoException e) {
- e.printStackTrace();
- }
MongoDB設定存取權限、設定使用者、在Java中使用者名稱密碼訪問