以下操作基于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();
- }
时间: 2024-10-18 05:06:43