java连接带密码的mongodb集群

阅读更多

当mongodb增加了密码登录验证之后,原来使用的java连接mongo的方式需要进行改变,主要是增加用户和密码的属性到连接里。

    List 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 credentialsList)
5.MongoClient(ServerAddress addr, MongoClientOptions options)
6.MongoClient(ServerAddress addr, List credentialsList, MongoClientOptions options)
7.MongoClient(List seeds)
8.MongoClient(List seeds, List credentialsList)
9.MongoClient(List seeds, MongoClientOptions options)
10.MongoClient(List seeds, List credentialsList, MongoClientOptions options)
11.MongoClient(MongoClientURI uri)

 可以根据具体的参数来创建对应的mongoClient。

 

你可能感兴趣的:(mongodb,java,验证)