Mongodb存在三种级别的分布式配置:主从配置、集群配置以及集群分片配置,建议咱们采用集群配置。mongodb
这种方式简单灵活,可用于备份、故障恢复,读扩展。为了平衡负载,通常经过读写分离模式,即主库写、从库读。缺点是若是主库down了,就不能写了,不会自动恢复。数据库
4. 执行rs.initiate(config_rs),成功后执行rs.status()便可看到配置的集群。等全部节点的“stateStr”为“Primary”或者“secondary”则集群同步好了。服务器
5. 以后若是要添加或者删除节点,使用rs.add(hostportstr), rs.remove(hostportstr)分布式
在集群分两类节点一个Primary和多个secondary(使用rs.isMaster()看节点的类型),Primary可读写,secondary只能读。当Primary 出错时,剩下的secondary会推举一个成为Primary,当出错的Primary恢复正常时会自动添加到集群并成为secondary。性能
6. MongoDB.Driver 的连接配置:blog
mongodb://localhost:3000,localhost:3001,localhost:3002/?replicaSet=rs&readPreference=primaryPreferred,若是须要更好的性能能够使用 readPreference= secondaryPreferred实现读写分离。rem
mongod.exe --shardsvr --replSet shard-a --dbpath "..\data\rs-a-1" --port 3000get
mongod.exe --shardsvr --replSet shard-a --dbpath "..\data\rs-a-2" --port 3001同步
mongod.exe --shardsvr --replSet shard-a --dbpath "..\data\rs-a-3" --port 3002it
config_rsa={_id:'shard-a',members:[{_id:0,host:'127.0.0.1:3000'},{_id:1,host:'127.0.0.1:3001'},{_id:2,host:'127.0.0.1:3002'}]}
rs.initiate(config_rsa)
2. 建立集群shard-b
mongod.exe --shardsvr --replSet shard-b --dbpath "..\data\rs-b-1" --port 30100
mongod.exe --shardsvr --replSet shard-b --dbpath "..\data\rs-b-2" --port 30101
mongod.exe --shardsvr --replSet shard-b --dbpath "..\data\rs-b-3" --port 30102
config_rsb={_id:'shard-b',members:[{_id:0,host:'127.0.0.1:30100'},{_id:1,host:'127.0.0.1:30101'},{_id:2,host:'127.0.0.1:30102'}]}
rs.initiate(config_rsb)
3. 启动配置服务器
mongod.exe --configsvr --dbpath "..\data\config-1" --port 27019
mongod.exe --configsvr --dbpath "..\data\config-2" --port 27020
mongod.exe --configsvr --dbpath "..\data\config-3" --port 27021
4. 启动Mongos(也能够多个)
Mongos.exe --configdb localhost:27019,localhost:27020,localhost:27021 --port 40000
把分片shard-a, shard-b添加到分片集群中:(使用mongo.exe登陆Mongos)
sh.addShard("shard-a/127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002")
sh.addShard("shard-b/127.0.0.1:30100,127.0.0.1:30101,127.0.0.1:30102")
5. 开启分片集合(登陆到Mongos)
sh.enableSharding("UserSubscribe_DB")
sh.shardCollection("UserSubscribe_DB.Sector",{_id:1})
6. 查看Mongos状态
sh.status
db.getSiblingDB("config").databases.find():查看分片数据库的设置
db.getSiblingDB("config").collections.find():查看分片集合的设置
7. MongoDB.Driver 的连接配置
mongodb://localhost:40000/
8. 对于已有非分片数据,再使用分片集合的方案
首先把现有数据导出,而后在根据以上过程配置分片集群和为库开启分片(选择合适的键进行分片),最后经过Mongos导入数据。这样经过Mongos就能访问了。