上一篇文章讲了简单分片的配置,想查看的可以点这个链接查看:https://blog.csdn.net/m0_37294207/article/details/123646170
mongodb简单分片解决了海量存储和动态扩容的问题,但在实际生产环境需要能高可靠、高可用。因此要有一个Replica Sets + Sharding的解决方案,对分片做集群。
- Shard:
使用 Replica Sets,确保每个数据节点都具有备份、自动容错转移、自动恢复能力。
- Config:
使用 3 个配置服务器,确保元数据完整性。
- Route:
使用 3 个路由进程,实现负载平衡,提高客户端接入性能。
1、在测试之前,先简单描述一下本机测试环境的地址跟端口号,如下:
服务1 | 服务2 | 服务3 | ||
---|---|---|---|---|
shard1 | 127.0.0.1:27019 | 127.0.0.1:27119 | 127.0.0.1:27219 | shard1的集群 |
shard2 | 127.0.0.1:27020 | 127.0.0.1:27120 | 127.0.0.1:27220 | shard2的集群 |
config | 127.0.0.1:27018 | 127.0.0.1:27118 | 127.0.0.1:27218 | 配置服务器的集群 |
route | 127.0.0.1:27017 | 127.0.0.1:27117 | 127.0.0.1:27217 | 3个路由进程 |
根据上面表格,服务2,服务3,是基于服务1的集群扩展。
2、配置shard
shard1的执行命令如下:
mongod -shardsvr -replSet shard1 -port 27019 -dbpath=E:\mongodb\data\db1
mongod -shardsvr -replSet shard1 -port 27119 -dbpath=E:\mongodb\data\db2
mongod -shardsvr -replSet shard1 -port 27219 -dbpath=E:\mongodb\data\db3
启动完数据节点后,登录27019节点,添加副本集,操作如下
mongo -port 27019
config={_id:'shard1',members:[{_id:0,host:'127.0.0.1:27019'},{_id:1,host:'127.0.0.1:27119'},{_id:2,host:'127.0.0.1:27219'}]}
rs.initiate(config)
注:这里使用config指定host的写法为127.0.0.1:27019,否则primary默认节点是localhost:27019,会引起不必要的麻烦,如下图。
shard2的操作步骤同shard1。
3、配置config
mongod -configsvr -dbpath=E:\mongodb\data\config1 -port 27018 -replSet config1
mongod -configsvr -dbpath=E:\mongodb\data\config2 -port 27118 -replSet config1
mongod -configsvr -dbpath=E:\mongodb\data\config3 -port 27218 -replSet config1
登录其中一个节点,添加副本集,具体操作如shard1。
4、配置route
mongos -configdb=config1/127.0.0.1:27018,127.0.0.1:27118,127.0.0.1:27218 -port 27017
mongos -configdb=config1/127.0.0.1:27018,127.0.0.1:27118,127.0.0.1:27218 -port 27117
mongos -configdb=config1/127.0.0.1:27018,127.0.0.1:27118,127.0.0.1:27218 -port 27217
注:-configdb要指定副本集的名字,在这里是config1
登录其中一个节点,将shard添加进来,命令如下:
db.runCommand({addshard:"shard1/127.0.0.1:27019,127.0.0.1:27119,127.0.0.1:27219"})
db.runCommand({addshard:"shard2/127.0.0.1:27020,127.0.0.1:27120,127.0.0.1:27220"})
之后,对需要进行分片的collection进行分片配置,在这里博主用test数据库的layne表做分片。
具体操作如下:
db.runCommand({ enablesharding:"test" })
db.runCommand({shardcollection:"test.layne",key:{_id:1}}) //制定shard key为:_id
查看layne表的状态可知,此时已经打开了分片功能。
这里测试数据的分片写入就不测试了,感兴趣的可以自己测试一下。
5、总结
本文主要讲副本集+分片的集群搭建方式,先对分片,配置服务器做副本集,随后创建多个路由进程,实现负载平衡,提高客户端接入性能。
在测试过程中,需要注意的点就是分片的host的设置,不预先配置以127.0.0.1的IP,系统会默认用localhost。