java连接带密码的mongodb集群
程序员文章站
2022-06-15 18:44:56
...
当mongodb增加了密码登录验证之后,原来使用的java连接mongo的方式需要进行改变,主要是增加用户和密码的属性到连接里。
List<ServerAddress> addresses = null; MongoCredential credential = MongoCredential.createCredential(dbUser, dbName, dbPwd.toCharArray()); MongoClientOptions options = builder.build(); client = new MongoClient(addresses, Arrays.asList(credential),options); DB = client.getDB(dbName);
其中关键的是new MongoClient()这个构造函数,里面的参数可以根据需求进行设定,如:
1.MongoClient(String host, MongoClientOptions options) 2.MongoClient(String host, int port) 3.MongoClient(ServerAddress addr) 4.MongoClient(ServerAddress addr, List<MongoCredential> credentialsList) 5.MongoClient(ServerAddress addr, MongoClientOptions options) 6.MongoClient(ServerAddress addr, List<MongoCredential> credentialsList, MongoClientOptions options) 7.MongoClient(List<ServerAddress> seeds) 8.MongoClient(List<ServerAddress> seeds, List<MongoCredential> credentialsList) 9.MongoClient(List<ServerAddress> seeds, MongoClientOptions options) 10.MongoClient(List<ServerAddress> seeds, List<MongoCredential> credentialsList, MongoClientOptions options) 11.MongoClient(MongoClientURI uri)
可以根据具体的参数来创建对应的mongoClient。