port=47017
dbpath=/usr/local/mongodb/data/mongodb2
logpath=/usr/local/mongodb/log/mongodb2.log
logappend=true
fork=true
maxConns=5000
storageEngine=mmapv1
shardsvr=true #指定分片服务器角色
[root@localhost ~]# vim /etc/mongodb3.conf #部署第2个分片服务器
port=47018
dbpath=/usr/local/mongodb/data/mongodb3
logpath=/usr/local/mongodb/log/mongodb3.log
logappend=true
fork=true
maxConns=5000
storageEngine=mmapv1
shardsvr=true
[root@localhost ~]# /etc/init.d/mongodb mongodb2 start
[root@localhost ~]# /etc/init.d/mongodb mongodb3 start
[root@localhost ~]# sysctl -w vm.zone_reclaim_mode=0
[root@localhost ~]# echo never > /sys/kernel/mm/transparent_hugepage/enabled #开启大页面存储
[root@localhost ~]# echo never > /sys/kernel/mm/transparent_hugepage/defrag
[root@localhost ~]# mongos --port 27017 --fork --logpath=/usr/local/mongodb/bin/route.log --configdb 192.168.100.77:37017 --chunkSize 1
#解析
--port: #指定端口号,MongoDB默认端口为27017
--fork: #指定工作模式
--logpath: #日志路径
--configdb: #指定配置服务器
--chunkSize: #指定数据块大小
[root@localhost ~]# mongo --port 27017 #!!!!注意是27017
mongos> show dbs
config 0.031GB
local 0.031GBmongos> sh.status() #查看分片状态信息
--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
"clusterId" : ObjectId("5b964a6d17b453754b82ab72")
}
shards: #此时查看并没有分片服务器状态
active mongoses:
"3.2.1" : 1
balancer:
Currently enabled: yes
Currently running: no
Failed balancer rounds in last 5 attempts: 0
Migration Results for the last 24 hours:
No recent migrations
databases:
mongos> sh.addShard("192.168.100.77:47017")
mongos> sh.addShard("192.168.100.77:47018")
mongos> sh.status()
--- Sharding Status ---
……
shards: #查看分片服务器已经添加成功
{ "_id" : "shard0000", "host" : "192.168.100.77:47017" }
{ "_id" : "shard0001", "host" : "192.168.100.77:47018" }6、实现分片功能
mongos> use school
mongos> for(var i=1; i<=10000; i++) db.student.insert({"id":i,"name":"Jack"+i})
mongos> db.student.find().limit(5)
mongos> db.student.count() #查看总共10个条目
mongos> sh.status()
--- Sharding Status ---
……
databases:
{ "_id" : "school", "primary" : "shard0000", "partitioned" : false } #partitioned为"false"代表"school"数据库尚未分片
mongos> sh.enableSharding("school")
mongos> sh.status()
mongos> use school
mongos> db.student.createIndex({"id":1}) #创建索引,"1"代表升序;"-1"代表降序
mongos> sh.shardCollection("school.student",{"id":1}) #使用创建的索引对集合进行分片
mongos> sh.status()
mongos> use school
mongos> for(var i=1; i<=50000; i++) db.student2.insert({"id":i,"name":"Tom"+i})
mongos> db.student2.createIndex({"id":1})
mongos> sh.shardCollection("school.student2",{"id":1})
mongos> sh.status() #对应条目数范围指向相应的分片
mongos> db.student2.stats()
mongos> sh.addShardTag("shard0000","stu00")
mongos> sh.addShardTag("shard0001","stu01")mongos> sh.status()
[root@localhost mongodb]# mongo --port 37017