主要问题是:MongoDB集群分为复制集(replicaSet)与分片集(shardingSet),那么如何去连接这两种集群;
参考官方文档,我使用了最通用的方法:通过构造connection string来通用连接两种集群;
两种集群connection string的构造方法:replicaSet中选取primary节点与secondary节点,排除arbiter节点;shardingSet中选取mongos节点;
Mongo的connection string够着方法:
mongodb://[username:[email protected]]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
MongoClient连接池连接方法:
String uriString = getURIString(primary); MongoClient mongoClient = new MongoClient(new MongoClientURI(uriString)); //根据MongoClient获取该集群下的Database Name MongoIterable<String> allDatabases = mongoClient.listDatabaseNames();
集群连接的官方文档参考:https://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/connect-to-mongodb/
connection string URI format:https://docs.mongodb.com/manual/reference/connection-string/
原文地址:https://www.cnblogs.com/jayinnn/p/10219955.html
时间: 2024-10-01 23:29:57