MongoDB集群搭建-分片

一.场景:

1,机器的磁盘不够用了。使用分片解决磁盘空间的问题。

2,单个mongod已经不能满足写数据的性能要求。通过分片让写压力分散到各个分片上面,使用分片服务器自身的资源。

3,想把大量数据放到内存里提高性能。和上面一样,通过分片使用分片服务器自身的资源。

 

二.搭建步骤:

1.准备服务器:

MongoDB集群搭建-分片

 

2.分片服务配置:【sharding】

上面准备的服务器有三台,每台机器上面都按照如下步骤安装分片服务,分片服务其实就是一个mongod进程;

下面我们就以192.168.0.106服务器为例子:

分片服务配置步骤:

(1)创建分片服务所需的文件目录:

配置目录:D:\mongodb_home\config

数据目录:D:\mongodb_home\data\shard

日志目录:D:\mongodb_home\logs

批处理目录:D:\mongodb_home\shells

 

(2)创建配置文件:(shard.conf文件)

目录:D:\mongodb_home\config\shard.conf

#shard.conf
dbpath=D:\mongodb_home\data\shard
logpath=D:\mongodb_home\logs\shard.log
journal=true
bind_ip=192.168.0.106
port=40000
shardsvr=true

 

(3)创建shell文件::(installShardServer.bat文件)

目录:D:\mongodb_home\shells\installShardServer.bat

#installShardServer.bat
d:
cd D:\mongodb_home\Server\3.6\bin
mongod.exe --config D:\mongodb_home\config\shard.conf --install

 

(4)安装分片服务:

目录:D:\mongodb_home\shells\installShardServer.bat

双击 installShardServer.bat来安装或启动服务;

分片注意:

其他两台机器,同上步骤配置即可。

配置文件更换ip地址即可;

 

3.配置服务配置:【config】

下面我们就以创建配置服务1为例子:

注意:mongodb3.6的特殊要求。

配置服务至少3个,只有一个的时候会报错误。

配置服务必须是副本集;

 

配置服务配置步骤:

(1)创建配置服务所需的目录:

配置目录:D:\mongodb_home\config

数据目录:D:\mongodb_home\data\config0

日志目录:D:\mongodb_home\logs

批处理目录:D:\mongodb_home\shells

 

(2)创建配置文件:

目录:D:\mongodb_home\data\config0\config0.conf

#config0.conf
dbpath=D:\mongodb_home\data\config0
logpath=D:\mongodb_home\logs\config0.log
journal=true
bind_ip=192.168.0.106
port=20000
replSet=testRs
configsvr=true

 

(3)创建shell文件:

目录:D:\mongodb_home\shells\installConfigServer0.bat

d:
cd D:\mongodb_home\Server\3.6\bin
mongod.exe --config D:\mongodb_home\config\config0.conf

 

(4)安装配置服务1:

目录:D:\mongodb_home\shells\installConfigServer0.bat

双击 installConfigServer0.bat来安装或启动服务;

配置服务注意:

配置服务使用端口来区分:

其他两个配置服务,同上步骤配置即可。

配置服务1端口:20000

配置服务2端口:21000

配置服务3端口:22000

 

4.路由服务配置:【route】

(1)创建路由服务所需的目录:

配置目录:D:\mongodb_home\config

日志目录:D:\mongodb_home\logs

 

(2)创建路由配置文件:

目录:D:\mongodb_home\config\route.conf

#route.conf
logpath=D:\mongodb_home\logs\route.log
bind_ip=192.168.0.106
port=30000
configdb=testRs/192.168.0.106:20000,192.168.0.106:21000,192.168.0.106:22000

注意:

路由配置文件中,不需要dbpath因为路由不存储数据。

路由配置文件中,最重要的是configdb,configdb是配置服务的地址

testRs是副本集的名称;

 

(3)创建路由shell文件:

目录:D:\mongodb_home\shells\InstallRouteServer.bat

#InstallRouteServer.bat
d:
cd D:\mongodb_home\Server\3.6\bin
mongos.exe --config D:\mongodb_home\config\route.conf

 

(4)安装路由服务:

目录:D:\mongodb_home\shells\InstallRouteServer.bat

双击 InstallRouteServer.bat来安装或启动服务;

 

(5)连接路由服务测试:

任意一台装mongodb的电脑即可:注意防火墙

通过mongodb中的mongo来连接路由服务【mongos】:

MongoDB集群搭建-分片

 

测试结果:

显示如下代码连接成功了!

MongoDB集群搭建-分片

 

5.分片:【核心】

(1)添加分片:

sh.addShard(“192.168.0.233:20000”) 
sh.addShard(“192.168.0.234:21000”) 
sh.addShard(“192.168.0.106:22000”) 

(2)查看分片信息:

sh.status() 

(3)数据库启用分片

School是数据库名称

sh.enableSharding('School')

(4)集合分片,设置片键

Name 集合中的键;

sh.shardCollection('School'.StudentInfo',{'Name':1})   

 

分类:

技术点:

相关文章: