部署配置服务器:configsvr
先生成.conf文件
bash
mkdir -p /data/mongodb/configsvr
vim /data/mongodb/configsvr/configsvr.conf
systemLog:
destination: file
logAppend: true
path: /data/mongodb/configsvr/configsvr.log
storage:
dbPath: /data/mongodb/configsvr
journal:
enabled: true
processManagement:
fork: true
net:
port: 27018
bindIp: 0.0.0.0
replication:
replSetName: myconfig
sharding:
clusterRole: configsvr
启动服务: mongod -f /data/mongodb/configsvr/configsvr.conf
配置副本集:
bash
mongosh 127.0.0.1:27018
use admin
config = { _id:"myconfig",
configsvr: true,
members:[
{_id:0,host:"192.168.11.137:27018"}, {_id:1,host:"192.168.11.200:27018"}
]
}
rs.initiate(config)
rs.status()
部署数据分片服务器:
副本名称:shard1
bash
mkdir -p /data/mongodb/shardsvr1
vim /data/mongodb/shardsvr1/shardsvr.conf
systemLog:
destination: file
logAppend: true
path: /data/mongodb/shardsvr1/shardsvr.log
storage:
dbPath: /data/mongodb/shardsvr1/
journal:
enabled: true
processManagement:
fork: true
net:
port: 27017
bindIp: 0.0.0.0
replication:
replSetName: shard1
sharding:
clusterRole: shardsvr
配置数据副本集:
bash
mongosh 127.0.0.1:27017
use admin
config = { _id:"shard1",
members:[
{_id:0,host:"192.168.11.137:27017"},
{_id:1,host:"192.168.11.200:27017"}
]
}
rs.initiate(config)
rs.status()
部署Router (mongos)服务器:
bash
mkdir -p /data/mongodb/router
vim /data/mongodb/router/router.conf
systemLog:
destination: file
logAppend: true
path: /data/mongodb/router/router.log
processManagement:
fork: true
net:
port: 27019
bindIp: 0.0.0.0
sharding:
configDB: myconfig/192.168.11.137:27018,192.168.11.200:27018
启动命令:mongos -f /data/mongodb/router/router.conf
为了高可用,你可以在另一台机器,再启动一个router实例(router开启多个实例,是不需要组成副本集的)
bash
mongosh 127.0.0.1:27019
use admin
sh.addShard("shard1/192.168.11.137:27017,192.168.11.200:27017")
sh.status()
sh.addShard 把副本集分片,添加到mongos当中
开启数据库分片功能:
sh.enableSharding("MyTestDB")
对集合进行分片初始化:
sh.shardCollection("MyTestDB.UserInfo" , {_id: 'hashed'}) //用哈希算法进行分片
.net连接router:
var client = new MongoClient("mongodb://router1IP:port,router2IP:port");