赞
踩
概念
MongoDB是文档数据库,存储都是类似json的Bosn文件。
json与Bosn区别
MongoDB与传统数据库的对比
SQL术语/概念 | MongoDB术语/概念 | 解释说明 |
---|---|---|
database | database | 数据库 |
table | collection | 数据库表\集合 |
row | document | 行\文档 |
colum | field | 数据字段\域 |
index | index | 索引 |
table joins | 表连接\MongoDB没有表连接 | |
primary key | primary key | 主键\MongoDB自动将_id字段设置主键 |
场景
主要应用在微服务系统中。
微服务+数据库的方式
如图:
缺陷
如果客户端同时获得商品信息和订单信息,会同时发出两次微服务查询才能获取到数据。
1、如果其中的一个微服务宕机,无法查询数据
2、如果客户端查询数据的并大量比较大,这样会导致系统出现性能问题。
方案
使用MongoDB;如图:
安装MongoDB
运行Mongodb
D:\SoftWare\MogoDB\bin>mongod.exe --config "D:\SoftWare\MogoDB\bin\mongod.cfg"
运行结果如图:
MongoDB Compass 免安装
直接到根目录下,运行MongoDBCompass.exe 即可。
点击Connect,如图:
安装Nuget包
MongoDB.Driver
项目实现
using MongoDB.Driver;
namespace MongoDB.Demo.Server
{
public class PersonServer : IPersonServer
{
private readonly IMongoCollection<Person> mongoCollection;
public PersonServer()
{
var client = new MongoClient("mongodb://localhost:27017");
mongoCollection = client.GetDatabase("PersonDB").GetCollection<Person>("person");
}
/// <summary>
/// 添加数据
/// </summary>
/// <param name="per"></param>
public void Create(Person per)
{
mongoCollection.InsertOne(per);
}
}
}
namespace MongoDB.Demo.Server
{
public interface IPersonServer
{
void Create(Person per);
}
}
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
namespace MongoDB.Demo
{
public class Person
{
//设置自增长ID
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public string CreateById { get; set; }
public DateTime CreateByTime { get;set;}
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MongoDB.Demo", Version = "v1" });
});
services.AddTransient<IPersonServer, PersonServer>();
}
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Demo.Server;
namespace MongoDB.Demo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly IPersonServer personServer;
public HomeController(IPersonServer _personServer)
{
personServer = _personServer;
}
/// <summary>
/// 添加数据到MongoDB
/// </summary>
/// <param name="per"></param>
/// <returns></returns>
[HttpPost]
public IActionResult Post(Person per)
{
personServer.Create(per);
return Ok(per);
}
}
}
原理
所有的模块之间是分层次的,MongoDB官方共有五大类型模块:核心模块、配置模块、事件模块、HTTP模块、mail模块、stream模块,它们之间的关系如图:
在这5个模块中,配置模块和核心模块是与MongoDB框架密切相关的。而事件模块则是HTTP模块与mail模块的基础。HTTP模块和mail模块的“地位”类似,它们都是更关注应用层面。
WiredTiger架构设计
原理
当MongoDB接收数据并转换成Bosn文件后发起请求到WiredTiger引擎,WiredTiger接收请求并处理请求将数据存储到缓存中,在将缓存中的数据隔60s或者数据到达2G的时候同步到磁盘中。
主要是做了两件事情:
1、将数据保存到缓存中
为什么将数据保存到缓存中?
减少IO操作,提升性能。
2、将缓存同步到磁盘中
为什么隔60s或者2G的时候同步数据?
当并发量大时候,防止缓存处理数据的性能大于磁盘的时候,导致同步是数据出现丢失。
WiredTiger防止数据丢失原理
使用双写架构
如图:
新增一个缓冲区。相当于消息队列的角色。
当上游和下游性能不一致的时候可以使用缓冲区。【RabbitMQ,kafka等】
WiredTiger的索引结构
如图:
MongoDB中缓存和磁盘存储数据是通过B+tree的数据结构存储的,Root节点和Internal是存储索引数据【相当于一本书中的目录】,而leaf节点是用来存储数据的【相当于书中的页】。
using MongoDB.Driver;
namespace MongoDB.Demo.Server
{
public class PersonServer : IPersonServer
{
private readonly IMongoCollection<Person> mongoCollection;
public PersonServer()
{
var client = new MongoClient("mongodb://localhost:27017");
mongoCollection = client.GetDatabase("PersonDB").GetCollection<Person>("person");
}
}
}
/// <summary>
/// 添加数据
/// </summary>
/// <param name="per"></param>
public void Create(Person per)
{
mongoCollection.InsertOne(per);
}
/// <summary>
/// 获取集合数据
/// </summary>
/// <returns></returns>
public IEnumerable<Person> GetList()
{
return mongoCollection.Find(p => true).ToList();
}
/// <summary>
/// 分页查询
/// </summary>
/// <param name="pagesize">行数</param>
/// <param name="index">页数</param>
/// <returns></returns>
public IEnumerable<Person> GetDataByPage(int pagesize,int index)
{
return mongoCollection.Find(p => true).Skip((index - 1) * pagesize).Limit(pagesize).ToList();
}
/// <summary>
/// 获取集合数据并排序
/// </summary>
/// <returns></returns>
public IEnumerable<Person> GetList()
{
return mongoCollection.Find(p => true).SortBy(per => per.CreateByTime).ToList();
}
/// <summary>
/// 修改数据并添加新字段
/// </summary>
/// <param name="id"></param>
/// <param name="per"></param>
public void Update(string id, Person per)
{
var update = Builders<Person>.Update;
// update.AddToSet("modifybyid","admin");//新增字段 实体中必须有这个字段 否则查询的时候会报错
//mongoCollection.UpdateOne((p) => p.Id == id, update.AddToSet("modifybyid", "admin"));
//修改字段
mongoCollection.UpdateOne((p) => p.Id == id, update.Set("Name", per.Name));
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="id"></param>
public void delete(string id)
{
mongoCollection.DeleteOne((p) => p.Id == id);
}
/// <summary>
/// 创建索引
/// </summary>
/// <returns></returns>
public string CreateIndex()
{
var indexKeys = Builders<Person>.IndexKeys;
return _products.Indexes.CreateOne(indexKeys.Descending("字段名称"));
}
概念
MongoDB的复制集就是一份数据复制多份而已。如图:
作用
当一个MongoDB宕机后,还有其他的MongoDB实例可以提供使用。保证MongoDB的高可用。
MongoDB 主从节点架构图
实现
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\ReplicaSet-data\data-27018
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\ReplicaSet-log\mongodb-27018.log
# network interfaces
net:
port: 27018
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: rs0
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\ReplicaSet-data\data-27019
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\ReplicaSet-log\mongodb-27019.log
# network interfaces
net:
port: 27019
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: rs0
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\ReplicaSet-data\data-27020
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\ReplicaSet-log\mongodb-27020.log
# network interfaces
net:
port: 27020
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: rs0
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
mongod.exe -f D:\SoftWare\MogoDB\bin\ReplicaSet\mongod-27018.cfg
mongod.exe -f D:\SoftWare\MogoDB\bin\ReplicaSet\mongod-27019.cfg
mongod.exe -f D:\SoftWare\MogoDB\bin\ReplicaSet\mongod-27020.cfg
运行结果如图:
![在这里插入图片描述](https://img-blog.csdnimg.cn/dd00e1a161df4f8ca0a51a21efe51a5c.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQEDnpZ7lhpzlhpnku6PnoIE=,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
- 设置27018建立连接并设置为主节点,并添加从节点
#建立连接 在 bin 目录下 mongo.exe --host 127.0.0.1 --port 27018 #使用命令设置主节点 rs.initiate()
如图:
添加其他节点到Member中
rs.add("127.0.0.1:27019") rs.add("127.0.0.1:27020")
如图:
- 查看状态命令
rs.status()
日志文件:
"members" : [ { "_id" : 0, "name" : "127.0.0.1:27018", "health" : 1, "state" : 1, "stateStr" : "PRIMARY", "uptime" : 308, "optime" : { "ts" : Timestamp(1649306184, 3), "t" : NumberLong(1) }, "optimeDate" : ISODate("2022-04-07T04:36:24Z"), "lastAppliedWallTime" : ISODate("2022-04-07T04:36:24.437Z"), "lastDurableWallTime" : ISODate("2022-04-07T04:36:24.437Z"), "syncSourceHost" : "", "syncSourceId" : -1, "infoMessage" : "", "electionTime" : Timestamp(1649306012, 2), "electionDate" : ISODate("2022-04-07T04:33:32Z"), "configVersion" : 5, "configTerm" : 1, "self" : true, "lastHeartbeatMessage" : "" }, { "_id" : 1, "name" : "127.0.0.1:27019", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 137, "optime" : { "ts" : Timestamp(1649306184, 3), "t" : NumberLong(1) }, "optimeDurable" : { "ts" : Timestamp(1649306184, 3), "t" : NumberLong(1) }, "optimeDate" : ISODate("2022-04-07T04:36:24Z"), "optimeDurableDate" : ISODate("2022-04-07T04:36:24Z"), "lastAppliedWallTime" : ISODate("2022-04-07T04:36:24.437Z"), "lastDurableWallTime" : ISODate("2022-04-07T04:36:24.437Z"), "lastHeartbeat" : ISODate("2022-04-07T04:36:30.077Z"), "lastHeartbeatRecv" : ISODate("2022-04-07T04:36:29.665Z"), "pingMs" : NumberLong(0), "lastHeartbeatMessage" : "", "syncSourceHost" : "127.0.0.1:27018", "syncSourceId" : 0, "infoMessage" : "", "configVersion" : 5, "configTerm" : 1 }, { "_id" : 2, "name" : "127.0.0.1:27020", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 129, "optime" : { "ts" : Timestamp(1649306184, 3), "t" : NumberLong(1) }, "optimeDurable" : { "ts" : Timestamp(1649306184, 3), "t" : NumberLong(1) }, "optimeDate" : ISODate("2022-04-07T04:36:24Z"), "optimeDurableDate" : ISODate("2022-04-07T04:36:24Z"), "lastAppliedWallTime" : ISODate("2022-04-07T04:36:24.437Z"), "lastDurableWallTime" : ISODate("2022-04-07T04:36:24.437Z"), "lastHeartbeat" : ISODate("2022-04-07T04:36:30.077Z"), "lastHeartbeatRecv" : ISODate("2022-04-07T04:36:30.169Z"), "pingMs" : NumberLong(0), "lastHeartbeatMessage" : "", "syncSourceHost" : "127.0.0.1:27019", "syncSourceId" : 1, "infoMessage" : "", "configVersion" : 5, "configTerm" : 1 } ],
//只能从主节点中读取数据
var client = new MongoClient("mongodb://localhost:27018,localhost:27019,localhost:27020");
//可以从从节点读取数据
var client = new MongoClient("mongodb://localhost:27018,localhost:27019,localhost:27020/?readPreference=secondaryPreferred");
//或者
var client = new MongoClient("mongodb://localhost:27018,localhost:27019,localhost:27020");
client.WithReadPreference(ReadPreference.PrimaryPreferred);
//Primary:默认参数 只从主节点上读取数据
// PrimaryPreferred:大部分从主节点上读取数据,只有主节点不可用时从Secondary上读取数据
//Secondary:只从Secondary节点上读取数据操作,存在的问题是Secondary节点的数据会比Primary节点的数据旧,如果没有可用的从节点,读请求会抛出异常。
//SecondaryPreferred:优先从Secondary节点上读取数据,Secondary节点不可用时从主节点读取数据。
//Nearest:不管是主节点,Secondary节点,从网络延迟最低的节点数读取数据。
条件
当主主节点宕机后,从节点会给自己先投一票,然后再去其他节点拉票,谁的票数多,谁就是主节点。
如果从节点的票数一样多,内部会有一个心跳检测机制,再次进行选举、投票。
投票规则:票数超过半数才能成为主节点;【节点数量为奇数最佳】
概念
MongoDB内部拆分数据,分开存储。
如图:
核心角色:
落地
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\shard-27021
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\mongodb-27021.log
# network interfaces
net:
port: 27021
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: sharding1
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
## Enterprise-Only Options:
#auditLog:
#snmp:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\shard-27022
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\mongodb-27022.log
# network interfaces
net:
port: 27022
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: sharding1
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\shard-27023
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\mongodb-27023.log
# network interfaces
net:
port: 27023
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: sharding1
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
## Enterprise-Only Options:
#auditLog:
#snmp:
#在MongoDB的bin目录下执行
#启动服务
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27021.cfg
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27022.cfg
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27023.cfg
#连接27021,弄分配主从节点
mongo.exe --host 127.0.0.1 --port 27021
#初始化 27021 为主节点
rs.initiate()
#添加子节点
rs.add("127.0.0.1:27022")
rs.add("127.0.0.1:27023")
#查看节点状态
rs.status()
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\shard-27024
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\mongodb-27024.log
# network interfaces
net:
port: 27024
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: sharding2
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
## Enterprise-Only Options:
#auditLog:
#snmp:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\shard-27025
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\mongodb-27025.log
# network interfaces
net:
port: 27025
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: sharding2
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
## Enterprise-Only Options:
#auditLog:
#snmp:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\shard-27026
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\mongodb-27026.log
# network interfaces
net:
port: 27026
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: sharding2
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
## Enterprise-Only Options:
#auditLog:
#snmp:
#在MongoDB的bin目录下执行
#启动服务
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27024.cfg
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27025.cfg
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27026.cfg
#连接27024,弄分配主从节点
mongo.exe --host 127.0.0.1 --port 27024
#初始化 27024 为主节点
rs.initiate()
#添加子节点
rs.add("127.0.0.1:27025")
rs.add("127.0.0.1:27026")
#查看节点状态
rs.status()
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\ConfigServer\configserver-27010
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\ConfigServer\configserver-27010.log
# network interfaces
net:
port: 27010
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
#集群名称,如果不是同一个集群内的机器,请不要配置重复
replSetName: confset
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
## Enterprise-Only Options:
#auditLog:
#snmp:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\ConfigServer\configserver-27011
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\ConfigServer\configserver-27011.log
# network interfaces
net:
port: 27011
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
#集群名称,如果不是同一个集群内的机器,请不要配置重复
replSetName: confset
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
## Enterprise-Only Options:
#auditLog:
#snmp:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\SoftWare\MogoDB\shards-data\ConfigServer\configserver-27012
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\ConfigServer\configserver-27012.log
# network interfaces
net:
port: 27012
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
replication:
#集群名称,如果不是同一个集群内的机器,请不要配置重复
replSetName: confset
sharding:
#分片集群名称 当前实例的角色(configsvr:配置中心实例,shardsvr:分片实例)
clusterRole: shardsvr
## Enterprise-Only Options:
#auditLog:
#snmp:
#在MongoDB的bin目录下执行
#启动服务
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27010.cfg
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27011.cfg
mongod.exe -f D:\SoftWare\MogoDB\bin\shards\mongod-27012.cfg
#连接27010,弄分配主从节点
mongo.exe --host 127.0.0.1 --port 27010
#初始化 27021 为主节点
rs.initiate()
#添加子节点
rs.add("127.0.0.1:27011")
rs.add("127.0.0.1:27012")
#查看节点状态
rs.status()
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
#storage:
#dbPath: D:\SoftWare\MogoDB\ReplicaSet-data\data-27021
#journal:
#enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\SoftWare\MogoDB\shards-log\Router\Router-27000.log
# network interfaces
net:
port: 27000
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
#replication:
#replSetName: rs0
sharding:
configDB: confset/127.0.0.1:27011,127.0.0.1:27010,127.0.0.1:27012
## Enterprise-Only Options:
#auditLog:
#snmp:
#在 bin 目录下启动服务
mongos.exe -f D:\SoftWare\MogoDB\bin\shards\Router\mongod-27000.cfg
#建立连接
mongo.exe --host 127.0.0.1 --port 27000
#注册复制集【6个实例 127.0.0.1:27021\27022\27023\27024\27025\27026】到配置服务中
#用复制集名称批量注册 配置文件中的replSetName: sharding1
sh.addShard("sharding1/127.0.0.1:27021,127.0.0.1:27022,127.0.0.1:27023")
#查看状态
sh.status()
sh.addShard("sharding2/127.0.0.1:27024,127.0.0.1:27025,127.0.0.1:27026")
#查看状态
sh.status()
#多个路由 内部自带了负载均衡
var client = new MongoClient("mongodb://127.0.0.1:27000,,,,,,");
#启动路由服务,建立连接后,使用命令
#语法
sh.shardCollection("数据库名称.集合名称",{"分片键":"分片类型【hashed,默认是范围分片】"})
#如果回车这样执行会报错,设置分片规则是不允许用代码创建数据库,需要在路由里创建数据库才行,命令如下
sh.enableSharding("数据库名称")
sh.shardCollection("数据库名称.集合名称",{"分片键":"分片类型【hashed/(1或者-1),默认是范围分片(1为升序-1为降序)】"})
#一个集合只能由一个分片键
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。