mongodb集群模式:主從集群,副本集集群,分片集群

前言

數(shù)據(jù)量大了或者并發(fā)量上來了,單機(jī)肯定是抗不住的,這個時候要開始考慮使用集群了。mongodb目前為止支持三種集群模式:主從集群,副本集集群,分片集群。

主從集群

特性

1. 一主多從
2. 主負(fù)責(zé)讀寫
3. 從負(fù)責(zé)讀
4. 從通過異步同步主op日志同步主數(shù)據(jù)
5. 主掛無法自動恢復(fù)

架構(gòu)圖

image

實踐

規(guī)劃

一主兩從
ip端口配置
主節(jié)點:127.0.0.1:27021
從節(jié)點1:127.0.0.1:27022
從節(jié)點2:127.0.0.1:27023

啟動主節(jié)點
su -s /bin/bash -c "/usr/bin/mongod --master -f /etc/mongodb/27021.conf" mongod

啟動從節(jié)點
su -s /bin/bash -c "/usr/bin/mongod --slave --source 127.0.0.1:27021 -f /etc/mongodb/27022.conf" mongod
su -s /bin/bash -c "/usr/bin/mongod --slave --source 127.0.0.1:27021 -f /etc/mongodb/27023.conf" mongod

設(shè)置從節(jié)點可用
use admin
rs.slaveOk()

查看是否主節(jié)點
use admin
rs.isMaster()

查看主節(jié)點復(fù)制狀態(tài)信息
use admin
rs.printReplicationInfo()

查看從節(jié)點復(fù)制狀態(tài)信息
use admin
rs.printSlaveReplicationInfo()

replica set集群
特性

  1. n個不同類型節(jié)點組成
  2. 每個節(jié)點數(shù)據(jù)相同
  3. 建議至少有一個primary和兩個secondary節(jié)點
  4. 集群中只能有一個primary節(jié)點
  5. 寫請求都通過primary節(jié)點
  6. 支持自動故障恢復(fù)
  7. primary節(jié)點不可用時,通過投票選舉從secondary節(jié)點列表中選出primary節(jié)點,因此最好節(jié)點數(shù)量是奇數(shù)
  8. secondary節(jié)點從primary節(jié)點通過oplog異步方式同步數(shù)據(jù) 節(jié)點類型

primary
主節(jié)點,負(fù)責(zé)集群數(shù)據(jù)維護(hù),所有數(shù)據(jù)更新操作都通過主節(jié)點

**secondary **
從節(jié)點,從主節(jié)點復(fù)制數(shù)據(jù),提供讀請求響應(yīng)

arbiter
選舉節(jié)點,不保存數(shù)據(jù),只參與primary投票選舉

架構(gòu)圖

image

節(jié)點屬性說明

priority: 0 表示不是候選人,可以投票
hidden:true 對用戶端不可見,不可見的節(jié)點priority必須設(shè)置為0
votes: 1 投票權(quán)限 0表示不能投票

實踐

規(guī)劃

搭建3個節(jié)點的集群,一個primary,兩個secondary
ip和端口配置
host1: 127.0.0.1:27018
host2: 127.0.0.1:27019
host3: 127.0.0.1:27020
集群名: replSetTest0

啟動3個事例

單個實例的配置

#系統(tǒng)日志配置
systemLog:
    destination: file
    path: /var/log/mongodb/mongod_27018.log
    logAppend: true
    #quiet模式運行,建議設(shè)置為false,方便排查錯誤
    quiet: false
 
#進(jìn)程管理
processManagement:
    #進(jìn)程后臺運行
    fork: true
    #進(jìn)程pid文件
    pidFilePath: /var/log/mongodb/mongod_27018.pid
 
#網(wǎng)絡(luò)配置
net:
    #監(jiān)聽端口
    port: 27018
    #監(jiān)聽網(wǎng)卡 多個使用英文逗號隔開
    bindIp: 127.0.0.1
    #最大并發(fā)連接數(shù) 默認(rèn)65535
    maxIncomingConnections: 65535
    #驗證客戶端傳過來的數(shù)據(jù),文檔嵌套多時,對性能會有些影響
    wireObjectCheck: true
    #是否啟用ipv6,默認(rèn)不啟用
    ipv6: false
    unixDomainSocket:
        #是否啟用socket監(jiān)聽 默認(rèn)true
        enabled: true
        #socket保存目錄,默認(rèn)/tmp
        pathPrefix: /var/log/mongodb
        #socket文件權(quán)限,默認(rèn)0700
        filePermissions: 0700
    http:
        #是否啟用http服務(wù),默認(rèn)false,安全考慮線上環(huán)境要關(guān)閉
        enabled: false
        #是否啟用http jsonp,默認(rèn)false,即使http.enabled為false,只要此項為true,一樣可以訪問,安全考慮線上環(huán)境要關(guān)閉
        JSONPEnabled: false
        #是否啟用rest api接口,默認(rèn)false,安全考慮線上環(huán)境要關(guān)閉
        RESTInterfaceEnabled: false
    compression:
        #是否啟用數(shù)據(jù)壓縮
        compressors: snappy
 
#安全配置
security:
    #type:string
    #密鑰路徑,副本集和分片集群節(jié)點間授權(quán)時使用的密鑰
    keyFile: /var/log/mongodb/.replSetTest0Key
 
    #type:string
    #集群授權(quán)模式,默認(rèn)keyFile,值列表:keyFile,sendKeyFile,sendX509,x509
    clusterAuthMode: keyFile
 
    #type:string
    #是否開啟數(shù)據(jù)庫訪問RBAC權(quán)限控制,默認(rèn):disabled,僅對mongod命令有效
    authorization: enabled
 
    #type:boolean
    #是否開啟服端js執(zhí)行,默認(rèn)true,如果未開啟$where,group,mapreduce都不能使用
    javascriptEnabled: true
 
#存儲配置
storage:
    #type:string
    #數(shù)據(jù)庫數(shù)據(jù)存儲目錄,默認(rèn)/data/db
    dbPath: /data/mongodb/27018
 
    #type:boolean
    #啟動時是否嘗試重建索引,默認(rèn)true
    indexBuildRetry: true
 
    #journal日志
    journal:
        #type:boolean
        #Enable or disable the durability journal to ensure data files remain valid and recoverable.
        enabled: true
 
        #type:int
        #日志同步間隔,Values can range from 1 to 500 milliseconds.
        commitIntervalMs: 100
 
    #type:boolean
    #是否開啟一數(shù)據(jù)庫一目錄,默認(rèn)是false
    directoryPerDB: false
 
    #type:int
    #數(shù)據(jù)落地時間間隔,默認(rèn)為60秒,不能設(shè)置為0,一般使用默認(rèn)值即可
    syncPeriodSecs: 60
 
    #type:string
    ##存儲引擎,默認(rèn)wiredTiger,可選值 mmapv1,wiredTiger,inMemory
    engine: wiredTiger
 
    wiredTiger:
        engineConfig:
            #type:float
            #單個實例可用的數(shù)據(jù)緩存內(nèi)存大小,version >= 3.4默認(rèn):50% of RAM minus 1 GB, or 256 MB.
            cacheSizeGB: 0.25
 
            #type:string
            #WiredTiger journal數(shù)據(jù)壓縮格式,默認(rèn)snappy,可用的壓縮類型: none, snappy, zlib
            journalCompressor: snappy
 
            #type:boolean
            #索引文件分目錄存儲,默認(rèn)false,version >= 3.0后版本可用
            directoryForIndexes: false
        collectionConfig:
            #type:string
            #塊數(shù)據(jù)壓縮格式,默認(rèn)snappy,可用的壓縮類型:none, snappy, zlib
            blockCompressor: snappy
        indexConfig:
            #type:boolean
            #是否開啟索引prefix compression,默認(rèn)true
            prefixCompression: true #是否開啟索引prefix compression,默認(rèn)true
 
#operationProfiling操作性能分析
operationProfiling:
    #type:int
    #慢查詢時間單位毫秒,默認(rèn)100,如果開啟了profile,日志會保存到system.profile集合中
    slowOpThresholdMs: 100
 
    #type:string
    #性能分析模式,開啟會影響性能,謹(jǐn)慎操作。默認(rèn)off.
    #可選值1:off: Off. No profiling.
    #可選值2: slowOp:On. Only includes slow operations.
    #可選值3: all:On. Includes all operations.
    mode: slowOp
 
#replication復(fù)制配置
replication:
    #type:int
    #數(shù)字類型(單位M) replication op log 大小,64位系統(tǒng)默認(rèn)為可用磁盤的5%
    oplogSizeMB: 512
 
    #type:string
    #所屬replica set集群名稱
    replSetName: replSetTest0
 
#setParameter配置
setParameter:
    enableLocalhostAuthBypass: false

啟動

su -s /bin/bash -c "/usr/bin/mongod -f /etc/mongodb/27018.conf" mongod
su -s /bin/bash -c "/usr/bin/mongod -f /etc/mongodb/27019.conf" mongod
su -s /bin/bash -c "/usr/bin/mongod -f /etc/mongodb/27020.conf" mongod

mongod -f /etc/mongodb/27018.conf --shutdown

集群初始化

mongo --port 27018
rs.initiate(
   {
      _id: "replSetTest0",
      version: 1,
      members: [
         { _id: 0, host : "127.0.0.1:27018" },
         { _id: 1, host : "127.0.0.1:27019" },
         { _id: 2, host : "127.0.0.1:27020" }
      ]
   }
)

設(shè)置從節(jié)點可用
mongo --port 27018(填寫實際的從節(jié)點地址)
rs.slaveOk()

查看集群狀態(tài)
mongo --port 27018
rs.status()

查看是否primary節(jié)點
mongo --port 27018
rs.isMaster()

查看集群配置
mongo --port 27018
rs.conf()

添加節(jié)點
mongo 主節(jié)點地址
rs.add({} | host地址)

刪除節(jié)點
mongo 主節(jié)點地址
刪除前,建議先停止這個節(jié)點的服務(wù)
rs.remove(hostname)

更改集群配置
mongo 主節(jié)點地址
rs.reconfig({},{})

分片集群

選定一個或多個key,按照選定的key進(jìn)行數(shù)據(jù)分割,分割后的數(shù)據(jù)分別保存在不同的mongodb副本集中,這個是分片的基本思路。
分片思路可以水平擴(kuò)展機(jī)器,根據(jù)業(yè)務(wù)需要擴(kuò)展任意多的機(jī)器。讀寫壓力分散到集群不同的機(jī)器中。

架構(gòu)圖

image

組件

配置server

副本集集群,分片信息,用戶授權(quán)信息,配置信息等都保存在這里

分片server

單個獨立的mongod實例或者副本集集群,存放真實的數(shù)據(jù)

路由server

處理客戶端連接請求,路由到存放數(shù)據(jù)的分片server,合并分片server的數(shù)據(jù),返回給客戶端

分片策略

支持類型

哈希分片

對分片key使用某種哈希算法,根據(jù)哈希值確定數(shù)據(jù)插入哪個分片server中

特點

數(shù)據(jù)離散性好,能均勻分布在不同的分片server中
不適合根據(jù)范圍查詢的情況

范圍分片

對分片key的值通過范圍確定存儲的分片server

特點

數(shù)據(jù)離散性可能不好,可能會造成熱點數(shù)據(jù)在某個分片server中
適合范圍查詢的情況

限制

分片key確定后不能更改
分片key必須設(shè)置索引,如果不是,設(shè)置分片key時,mongod會自動創(chuàng)建

原則

1. 選擇值多樣性的key,盡可能分散,避免數(shù)據(jù)文檔集中到某些分片server中
2. 考慮以后是否會數(shù)據(jù)分組,數(shù)據(jù)分組時分組key需要是分片key或者分片組合key的前綴
3. 選擇合適的分片類型,不同的分片類型適用的場景不一樣
4. 當(dāng)必須選擇值重復(fù)頻率高的key時,可以考慮選擇組合key

實踐

規(guī)劃

考慮到只是實踐使用,配置server副本集只用一臺,分片server副本集也只用一臺
1臺配置server: 127.0.0.1:27024(副本集集群,集群名:shardClusterCfgServerReplSet0)
1臺路由server: 127.0.0.1:27025
2臺分片server:127.0.0.1:27026(副本集集群,集群名:shardClusterShardServerReplSet0),127.0.0.1:27027(副本集集群,集群名:shardClusterShardServerReplSet1)

啟動配置server

sharding:
    clusterRole: configsvr
replication:
    replSetName: shardClusterCfgServerReplSet0
 
su -s /bin/bash -c "/usr/bin/mongod -f /etc/mongodb/27024.conf" mongod
 
rs.initiate(
  {
    _id: "shardClusterCfgServerReplSet0",
    configsvr: true,
    members: [
      { _id : 0, host : "127.0.0.1:27024" }
    ]
  }
)

啟動分片server

sharding:
    clusterRole: shardsvr
replication:
    replSetName: shardClusterShardServerReplSet0
 
su -s /bin/bash -c "/usr/bin/mongod -f /etc/mongodb/27026.conf" mongod
su -s /bin/bash -c "/usr/bin/mongod -f /etc/mongodb/27027.conf" mongod
 
rs.initiate(
  {
    _id: "shardClusterShardServerReplSet1",
    members: [
      { _id : 0, host : "127.0.0.1:27027" }
    ]
  }
)

啟動路由server

su -s /bin/bash -c "/usr/bin/mongos -f /etc/mongodb/27025.conf" mongod

增加或者移除分片最好停服操作,減少數(shù)據(jù)不一致的可能性
使用配置server用戶登錄mongos進(jìn)行操作

#系統(tǒng)日志配置
systemLog:
    destination: file
    path: /var/log/mongodb/mongod_27025.log
    logAppend: true
    #quiet模式運行,建議設(shè)置為false,方便排查錯誤
    quiet: false
 
#進(jìn)程管理
processManagement:
    #進(jìn)程后臺運行
    fork: true
    #進(jìn)程pid文件
    pidFilePath: /var/log/mongodb/mongod_27025.pid
 
#網(wǎng)絡(luò)配置
net:
    #監(jiān)聽端口
    port: 27025
    #監(jiān)聽網(wǎng)卡 多個使用英文逗號隔開
    bindIp: 127.0.0.1
    #最大并發(fā)連接數(shù) 默認(rèn)65535
    maxIncomingConnections: 65535
    #驗證客戶端傳過來的數(shù)據(jù),文檔嵌套多時,對性能會有些影響
    wireObjectCheck: true
    #是否啟用ipv6,默認(rèn)不啟用
    ipv6: false
    unixDomainSocket:
        #是否啟用socket監(jiān)聽 默認(rèn)true
        enabled: true
        #socket保存目錄,默認(rèn)/tmp
        pathPrefix: /var/log/mongodb
        #socket文件權(quán)限,默認(rèn)0700
        filePermissions: 0700
    http:
        #是否啟用http服務(wù),默認(rèn)false,安全考慮線上環(huán)境要關(guān)閉
        enabled: false
    compression:
        #是否啟用數(shù)據(jù)壓縮
        compressors: snappy
 
#安全配置
security:
    #type:string
    #密鑰路徑,副本集和分片集群節(jié)點間授權(quán)時使用的密鑰
    keyFile: /var/log/mongodb/.replSetTest0Key
 
    #type:string
    #集群授權(quán)模式,默認(rèn)keyFile,值列表:keyFile,sendKeyFile,sendX509,x509
    clusterAuthMode: keyFile
 
#setParameter配置
setParameter:
    enableLocalhostAuthBypass: false
 
#分片配置
sharding:
    #type:string
    #配置server,多個使用英文逗號分開
    configDB: shardClusterCfgServerReplSet0/127.0.0.1:27024

添加分片server

添加分片操作會觸發(fā)數(shù)據(jù)遷移,遷移過程中對數(shù)據(jù)庫性能會有些影響
sh.addShard("shardClusterShardServerReplSet0/127.0.0.1:27026")
sh.addShard("shardClusterShardServerReplSet1/127.0.0.1:27027")

開啟數(shù)據(jù)庫分片

sh.enableSharding("test")

設(shè)置集合分片key

sh.shardCollection("test.people",{_id:1})

移除分片server

移除分片server前需要先遷移分區(qū)數(shù)據(jù)到其它分片,為了保證整個集群性能,遷移過程中會占用比較小的資源,網(wǎng)絡(luò)帶寬和數(shù)據(jù)量大小會影響遷移時間,
可能需要幾分鐘到幾天不等

移除步驟

step1 確定遷移進(jìn)程開啟
sh.getBalancerState()
返回true表示開啟

step2 確定需要刪除分片的名字
db.adminCommand( { listShards : 1 } )
_id字段值為分片名稱

step3 遷移分片數(shù)據(jù)到其它分片
db.adminCommand({removeShard:"shardClusterShardServerReplSet1"})

{
    "msg" : "draining started successfully",
    "state" : "started",
    "shard" : "shardClusterShardServerReplSet1",
    "note" : "you need to drop or movePrimary these databases",
    "dbsToMove" : [
        "test"
    ],
    "ok" : 1
}

step4 查看遷移狀態(tài)
db.adminCommand({removeShard:"shardClusterShardServerReplSet1"})

{
    "msg" : "draining ongoing",
    "state" : "ongoing",
    "remaining" : {
        "chunks" : NumberLong(0),
        "dbs" : NumberLong(1)
    },
    "note" : "you need to drop or movePrimary these databases",
    "dbsToMove" : [
        "test"
    ],
    "ok" : 1
}

step5 遷移未分片的數(shù)據(jù)
分片數(shù)據(jù)遷移完成后執(zhí)行
返回的狀態(tài)列表字段remaining.chunks為0時表示遷移完成
如果沒有未分片的數(shù)據(jù)庫,不需要執(zhí)行這個步驟
返回的狀態(tài)列表有一個字段dbsToMove,這個字段的內(nèi)容為需要遷移的未分片的數(shù)據(jù)庫,不為空時需要執(zhí)行遷移操作

use admin
db.runCommand({movePrimary:"test", to:"shardClusterShardServerReplSet0"})
db.runCommand({flushRouterConfig:1})

step6 數(shù)據(jù)遷移完成確認(rèn)
前面步驟都執(zhí)行完成后執(zhí)行

db.adminCommand({removeShard:"shardClusterShardServerReplSet1"})
{
    "msg" : "removeshard completed successfully",
    "state" : "completed",
    "shard" : "shardClusterShardServerReplSet1",
    "ok" : 1
}

集群相關(guān)操作

連接mongos
mongo --host mongos_host --port mongos_port

查看狀態(tài)
sh.status()

顯示開啟分區(qū)的數(shù)據(jù)庫
use config
db.databases.find({partitioned:true})

顯示分片server列表
db.adminCommand( { listShards : 1 } )

查看數(shù)據(jù)遷移進(jìn)程狀態(tài)
sh.getBalancerState()

備注

  1. 第一次初始化時禁用權(quán)限判斷,添加好用戶之后再開啟
  2. 增刪改只能在主節(jié)點操作
  3. 集群使用的密碼不能超過1K且只能是base64編碼字符集
  4. keyFile文件權(quán)限不能開放給所在組成員和其他組成員
  5. 生成隨機(jī)密碼:openssl rand -base64 741

參考資料

【1】Replication
https://docs.mongodb.com/manual/replication/

【2】Read Preference
https://docs.mongodb.com/manual/core/read-preference/

【3】Replica Set Members
https://docs.mongodb.com/manual/core/replica-set-members/

【4】Replica Set Elections
https://docs.mongodb.com/manual/core/replica-set-elections/

【5】Replica Set Data Synchronization
https://docs.mongodb.com/manual/core/replica-set-sync/

【6】Replica Set Oplog
https://docs.mongodb.com/manual/core/replica-set-oplog/

【7】Replica Set Deployment Architectures
https://docs.mongodb.com/manual/core/replica-set-architectures/

【8】Mongo Shell - Replication Methods
https://docs.mongodb.com/manual/reference/method/js-replication/

【9】Deploy a Replica Set
https://docs.mongodb.com/manual/tutorial/deploy-replica-set/

【10】Replica Set Configuration
https://docs.mongodb.com/manual/reference/replica-configuration/

【11】Rollbacks During Replica Set Failover
https://docs.mongodb.com/manual/core/replica-set-rollbacks/

【12】Change the Size of the Oplog
https://docs.mongodb.com/manual/tutorial/change-oplog-size/

【13】Resync a Member of a Replica Set
https://docs.mongodb.com/manual/tutorial/resync-replica-set-member/

【14】Replication Reference
https://docs.mongodb.com/manual/reference/replication/

【15】Write Concern
https://docs.mongodb.com/manual/reference/write-concern/

【16】Read Isolation, Consistency, and Recency
https://docs.mongodb.com/manual/core/read-isolation-consistency-recency/

【17】Master Slave Replication
https://docs.mongodb.com/manual/core/master-slave/

【18】分片集群
https://docs.mongodb.com/manual/sharding/

【19】分片-區(qū)域
https://docs.mongodb.com/manual/core/zone-sharding/

【20】分片-參考
https://docs.mongodb.com/manual/reference/sharding/

【21】分片-管理
https://docs.mongodb.com/manual/administration/sharded-cluster-administration/

【22】分片-均衡
https://docs.mongodb.com/manual/core/sharding-balancer-administration/

【23】分片-組件
https://docs.mongodb.com/manual/core/sharded-cluster-components/

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容