數據php
程序: 指令+數據html
關係型mysql
非關係型linux
https://db-engines.com/en/rankingweb
NoSQL是什麼?算法
NoSQL=Not Only SQLsql
1998年Carlo Strozzi首次提出(不提供SQL功能的關係型數據庫)mongodb
2009年Eric Evans再次提出NoSQL概念shell
NoSQL、Relational Database相鋪相成數據庫
NoSQL數據庫四你們族:
列存儲:Hbase
鍵值(Key-Value)存儲:Redis
圖像存儲:Neo4J
文檔存儲:MongoDB
RDBMS即關係數據庫管理系統(Relational Database Management System),是將數據組織成相關的行和列的系統,而管理關係數據庫的計算機軟件就是關係數據庫管理系統,經常使用軟件有Oracle、SQL Server等
高可擴展性
橫向擴展 也叫 水平擴展,用更多的節點支撐更大量的請求。 如成千上萬的螞蟻完成一項搬運工做
縱向擴展 又叫 垂直擴展,擴展一個點的能力支撐更大的請求。如利用1我的的能力,如蜘蛛俠逼停火車
分佈式計算
沒有複雜的關係
低成本
架構靈活
半結構化數據
開源
MongoDB是有開源產品的
On GitHub
Licensed under the AGPL
起源& 贊助by MongoDB公司
提供商業版licenses 許可
MongoDB與RDBMS最大的區別在於:沒有固定的行列組織數據結構
RDBMS MongoDB
table,view表格,視圖 collection 集合
row 行 document 文檔
index 索引 index
join 加入,鏈接,接合點 embedded document嵌套文檔
foreign key 外鍵 reference 參考,引用
partition 拆分,分區 shard分片 .
有外向裏: 數據庫à集合à文檔
層次關係:
--文檔(document)
--集合(collection)
--數據庫(database)
層次關係圖:
文檔型
--JSON
MongoDB 使用JSON(JavaScript ObjectNotation)文檔存儲記錄。
JSON數據庫語句能夠容易被解析
Web 應用大量使用
NAME-VALUE 配對,例如:
{
product: 「car」,
brand: 「Benz」,
color: 「blue」 }
--BSON
二進制的JSON,JSON文檔的二進制編碼存儲格式. 弱點是最大存取單元不能夠超過16M
BSON有JSON沒有的Date和BinData
MongoDB中document以BSON形式存放
> db.meeting.insert({meeting:"SHOUG June",Date:"2015-06-15"});
--靈活的數據格式
靈活歸靈活. 可是要符合應用邏輯規則
跨平臺
--Linux、Unix、Mac、Windows
--總體架構相同
MongoDB Server
--實例、數據庫及其對應關係
數據邏輯結構
--文檔、集合、數據庫
數據存儲
--元數據、實際數據
網站數據
緩存
大尺寸、低價值的數據
高伸縮性的場景
用於對象及JSON數據的存儲
下載地址:
文檔地址:
docs.mongodb.com
mongoing.com ##中文社區
版本支持平臺表
https://docs.mongodb.com/manual/installation/
http://www.mongoing.com/docs/installation.html#supported-platforms
mgdb3.2.8安裝步驟:
建立所需用戶和組
useradd mongodb
passwd mongod
(2)建立mongodb所需目錄結構
mkdir -p /mongodb/bin
mkdir -p /mongodb/conf
mkdir -p /mongodb/log
mkdir -p /mongodb/data
(3)上傳並解壓軟件到指定位置
mongodb-linux-x86_64-3.2.8.tgz
cd mongodb-linux-x86_64-3.2.8/bin/
cp * /mongodb/bin
(4)設置目錄結構權限
chown -R mongod:mongod /mongodb
(5)設置用戶環境變量
su - mongod
vi .bash_profile
export PATH=/mongodb/bin:$PATH
source .bashprofile
(6)啓動mongodb
mongod --dbpath=/mongodb/data --logpath=/mongodb/log/mongodb.log --port=27017 --logappend --fork
(7)登陸mongodb
[mongod@server2 ~]$ mongo
MongoDB shell version: 3.2.8
connecting to: test
>
>
(8)使用配置文件
mongod -f /mongodb/config/mongodb.conf
------------
vi /mongodb/config/mongodb.conf
logptah=
dbpath=
port=
logappend=
fork=
auth=
+++++++++++++++++++
(YAML模式:)
--
NOTE:
YAML does not support tab characters for indentation: use spaces instead.
--
systemLog:
destination: file
path: "/mongodb/log/mongod.log"
logAppend: true
storage:
journal:
enabled: true
dbPath: "<PATH>"
processManagement:
fork: true
pidFilePath: <string>
net:
bindIp: <ip>
port: <port>
setParameter:
enableLocalhostAuthBypass: false
security:
authorization: enabled
replication:
oplogSizeMB: <NUM>
replSetName: "<REPSETNAME>"
secondaryIndexPrefetch: "all"
sharding:
clusterRole: <string>
archiveMovedChunks: <boolean>
---for mongos only
replication:
localPingThresholdMs: <int>
sharding:
configDB: <string>
---
.........
++++++++++++++++++++++
(9)mongodb的關閉方式
---kill進程形式
$ kill -2 PID
原理:-2表示向mongod進程發送SIGINT信號。
或
$ kill -4 PID
原理:-4表示向mognod進程發送SIGTERM信號。
---自帶模式
admin> db.shutdownServer()
或
admin> db.adminCommand({shutdown:1})
或
$ mongod -f mongodb.conf --shutdown
killing process with pid: 1621
注:mongod進程收到SIGINT信號或者SIGTERM信號,會作一些處理
> 關閉全部打開的鏈接
> 將內存數據強制刷新到磁盤
> 當前的操做執行完畢
> ...
> 安全中止
!!!切記不可kill -9
> 數據庫直接關閉
> 數據丟失
> 數據文件損失
> 修復數據庫(成本高,有風險)
(1)redhat或cnetos6.2以上系統
(2)系統開發包完整
(3)ip地址和hosts文件解析正常
(4)iptables防火牆&SElinux關閉
(5)關閉hugepage大頁內存機制 https://docs.mongodb.com/manual/tutorial/transparent-huge-pages/
########################################################################
root用戶下
在vi /etc/rc.local最後添加以下代碼
if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
echo never > /sys/kernel/mm/transparent_hugepage/enabled
fi
if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi
檢查一下
[root@wu ~]# cat /sys/kernel/mm/transparent_hugepage/enabled
[always] madvise never
[root@wu ~]# cat /sys/kernel/mm/transparent_hugepage/defrag
[always] madvise never
[root@wu ~]# . /etc/rc.local ###從新加載下 . 或source下文件
[root@wu ~]# cat /sys/kernel/mm/transparent_hugepage/enabled
always madvise [never]
[root@wu ~]# cat /sys/kernel/mm/transparent_hugepage/defrag
always madvise [never]
其餘系統關閉參照官方文檔:https://docs.mongodb.com/manual/tutorial/transparent-huge-pages/
爲何要關閉?
透明大頁面(THP)是一種Linux內存管理系統,經過使用更大的內存頁面,能夠減小具備大量內存的計算機上的Translation Lookaside Buffer(TLB轉譯後備緩衝區 )查找的開銷。可是,數據庫工做負載一般在THP上表現不佳,由於它們每每具備稀疏而不是連續的內存訪問模式。您應該在Linux機器上禁用THP以確保使用MongoDB得到最佳性能。
############################################################################
加一塊20G的新磁盤備用 ######備選
/dev/sdb ,設置掛載點/mongodb,並將新磁盤掛在到
[root@web01 ~]# mkfs.ext4 /dev/sdb
[root@web01 ~]# mkdir /mongodb
[root@web01 ~]# mount /dev/sdb /mongodb/
[root@web01 ~]# blkid
/dev/sda1: UUID="2c37d13b-6fc4-4ef3-b178-aae2270e3b34" TYPE="ext4"
/dev/sda2: UUID="fcada1c8-bc9f-4a7b-b6d6-c45cc27d0e15" TYPE="swap"
/dev/sda3: UUID="8708eb7e-b0e9-4217-9ee6-920800d2c55f" TYPE="ext4"
/dev/sdb: UUID="07001c98-3ac3-46db-9b13-8463627f3d89" TYPE="ext4"
vi /etc/fstab
UUID=07001c98-3ac3-46db-9b13-8463627f3d89 /mongodb etxt4 defaults 0 0
mount -a
[root@web01 mongodb]# tar -zxvf mongodb-linux-x86_64-3.2.8.tgz
要求,自定義設置用戶、組ID
[root@web01 bin]# groupadd -g 801 mongod
[root@web01 bin]# useradd -u 802 -g mongod mongod
[root@web01 bin]# passwd mongod -------》123456
#### 注意:必定要mount以後再作----不掛新磁盤不用管
[root@web01 ~]# mkdir /mongodb/bin
[root@web01 ~]# mkdir /mongodb/data
[root@web01 ~]# mkdir /mongodb/log
[root@web01 ~]# mkdir /mongodb/conf
[root@web01 bin]# pwd
/mongodb/mongodb-linux-x86_64-3.2.8/bin
[root@web01 bin]# cp * /mongodb/bin/
[root@web01 bin]# chown -R mongod:mongod /mongodb/
------------------
[root@web01 ~]# su - mongod
[mongod@web01 ~]$ cd /mongodb/bin/
[mongod@web01 bin]$ ./mongod --logpath=/mongodb/log/mongodb.log --dbpath=/mongodb/data/ --fork --logappend
about to fork child process, waiting until server is ready for connections.
forked process: 1900
child process started successfully, parent exiting
[mongod@web01 ~]$ vi .bash_profile
export PATH=/mongodb/bin:$PATH
[mongod@web01 ~]$ . ./.bash_profile
或者
[mongod@web01 ~]$ source .bash_profile
[mongod@web01 ~]$ vi /mongodb/conf/mongod.conf
[mongod@web01 ~]$ cat /mongodb/conf/mongod.conf
dbpath=/mongodb/data
logpath=/mongodb/log/mongodb.log
logappend=true
fork=true
[mongod@web01 ~]$ mongo
MongoDB shell version: 3.2.8
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
2018-08-29T17:16:25.133+0800 I CONTROL [initandlisten]
2018-08-29T17:16:25.133+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
>
kill -2 PID
kill -4 PID
---kill進程形式
$ kill -2 PID
原理:-2表示向mongod進程發送SIGINT信號。
或
$ kill -4 PID
原理:-4表示向mognod進程發送SIGTERM信號。
admin> db.shutdownServer()
或
admin> db.adminCommand({shutdown:1})
或
$ mongod -f mongodb.conf --shutdown
---自帶模式
admin> db.shutdownServer()
或
admin> db.adminCommand({shutdown:1})
或
$ mongod -f mongodb.conf --shutdown
killing process with pid: 1621
注:mongod進程收到SIGINT信號或者SIGTERM信號,會作一些處理
> 關閉全部打開的鏈接
> 將內存數據強制刷新到磁盤
> 當前的操做執行完畢
> ...
> 安全中止
> 數據庫直接關閉
> 數據丟失
> 數據文件損失
> 修復數據庫(成本高,有風險)
####有時上傳格式不對 用dos2unix -k 文件名 轉換下內容格式 -k --keepdate 保持時間戳一致
能夠把腳本放在/etc/init.d/下 加權限執行
#!/bin/bash
#
#chkconfig: 2345 80 90
#description:mongodb
mongo_user=mongodb
MONGODIR=/mongodb
MONGOD=$MONGODIR/bin/mongod
#MONGO=$MONGODIR/bin/mongo
#DBDIR=$MONGODIR/data/data27017
#LOGPATH=$MONGODIR/log/mongodb.log
MONGOCONF=$MONGODIR/conf/mongod.conf
start() {
su - $mongo_user -c "$MONGOD -f $MONGOCONF"
}
stop() {
su - $mongo_user -c "$MONGOD -f $MONGOCONF --shutdown"
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
sleep 2
start
;;
*)
echo $"Usage: $0 {start|stop|restart}"
exit 1
esac
MongoDB數據庫默認是沒有用戶名及密碼的,即無權限訪問限制。爲了方便數據庫的管理和安全,需建立數據庫用戶.
https://www.mongodbmanager.com/
或者用 MongoVUE, 雲盤有破解包
su - mongod
mongo
mongo 127.0.0.1:port ### 其餘端口
++++++可能會出現的警告,說明大頁內存未關閉。
Server has startup warnings:
2017-09-09T11:49:58.483+0800 I CONTROL [initandlisten]
2017-09-09T11:49:58.483+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-09-09T11:49:58.484+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2017-09-09T11:49:58.484+0800 I CONTROL [initandlisten]
2017-09-09T11:49:58.484+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2017-09-09T11:49:58.484+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2017-09-09T11:49:58.484+0800 I CONTROL [initandlisten]
++++++
一、db類:當前實例管理
二、rs類: 複製集管理
三、sh類: 分片管理
[db/rs/sh].[關鍵字]()
db.[collection].xxx
db.log.drop()
show collections
use wordpress
db.[collection].[insert/delete/update/find]
(
)
for(i=0;i<10000;i++){ db.log.insert({"uid":i,"name":"mongodb","age":6,"date":new Date()}); }
建立
$ mongo
use admin
db.createUser(
{
user: "root",
pwd: "root123",
roles: [ { role: "root", db: "admin" } ]
}
)
驗證
db.auth('root','root123')
修改配置文件
vim mongod.conf
auth=true
重啓mongodb
注意順序;
不能先改配置文件重啓再加用戶,必須先建立用戶再 改配置文件重啓
登陸
[mongod@web01 ~]$ mongo -uroot admin -p
[mongod@web01 ~]$ mongo -uroot -p --authenticationDatabase admin
[mongod@web01 ~]$ mongo
> use admin
switched to db admin
> db.auth('root','root123')
mongo --help
mongo裏有命令補全功能, 自動切換大小寫字母
http://www.javashuo.com/article/p-kwsyehem-ko.html
help
KEYWORDS.help
KEYWORDS.[TAB]
> help
db.help() help on db methods db方法上的db.help()幫助
db.mycoll.help() help on collection methods 幫助收集方法
sh.help() sharding helpers sh.help()分片幫手
rs.help() replica set helpers rs.help()複製設置幫手
help admin administrative help 幫助管理員管理
help connect connecting to a db help 幫助鏈接到數據庫幫助
help keys key shortcuts 幫助鍵鍵的快捷方式
help misc misc things to know 幫助雜碎知道雜碎的事情
help mr mapreduce
show dbs show database names 顯示dbs顯示數據庫名稱
show collections show collections in current database 顯示集合顯示當前數據庫中的集合
show users show users in current database 顯示用戶顯示當前數據庫中的用戶
show profile show most recent system.profile entries with time >= 1ms顯示配置文件顯示最新系統。時間>= 1ms的概要條目
show logs show the accessible logger names 顯示日誌,顯示可訪問的日誌記錄器名稱
show log [name] prints out the last segment of log in memory, 'global' is default 顯示log [name]在內存中打印出日誌的最後一部分,'global'是默認值
use <db_name> set current database 使用<db_name>設置當前數據庫
db.foo.find() list objects in collection foo find()列表集合foo中的對象
db.foo.find( { a : 1 } ) list objects in foo where a == 1 db.foo。查找foo中a == 1的對象({a: 1})
it result of the last line evaluated; use to further iterate 最後一行的計算結果;用於進一步的迭代
DBQuery.shellBatchSize = x set default number of items to display on shell 設置默認顯示的項目數量
exit quit the mongo shell
查看當前db版本
test> db.version()
3.2.6
顯示當前數據庫
test> db
test
或
> db.getName()
test
查詢全部數據庫
test> show dbs
local 0.000GB
切換數據庫
> use local
switched to db local
顯示當前數據庫狀態
查看local數據
test> use local
switched to db local
local> db.stats()
查看當前數據庫的鏈接機器地址
查看當前鏈接的數據庫地址
> db.getMongo()
connection to 127.0.0.1
# mongo 192.168.1.24/admin
[mongod@mongodb ~]$ mongo 192.168.1.24/admin
MongoDB shell version: 3.2.6
connecting to: 192.168.1.24/admin
admin>
當use的時候,系統就會自動建立一個數據庫。若是use以後沒有建立任何集合。系統就會刪除這個數據庫。
//刪除test數據庫
test> show dbs
local 0.000GB
test 0.000GB
test> use test
switched to db test
test> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }
方法1:
admin> use app
switched to db app
app> db.createCollection('a')
{ "ok" : 1 }
app> db.createCollection('b')
{ "ok" : 1 }
> show collections 或者 show tables //查看當前數據庫下的全部集合
a
b
或
> db.getCollectionNames()
[ "a", "b" ]
方法2:當插入一個文檔的時候,一個集合就會自動建立。
admin> use app
switched to db app
app> db.c.insert({username:"mongodb"})
WriteResult({ "nInserted" : 1 })
app> show collections
a
b
c
app> db.c.find() ###查看數據
{ "_id" : ObjectId("5743c9a9bf72d9f7b524713d"), "username" : "mongodb" }
app> use app
switched to db app
app> db.createCollection('log')
{ "ok" : 1 }
app> db.log.drop() //刪除集合
//把log更名爲log1
app> db.log.renameCollection("log1")
{ "ok" : 1 }
app> show collections
a
b
c
log1
app>
app> for(i=0;i<10000;i++){ db.log.insert({"uid":i,"name":"mongodb","age":6,"date":new Date()}); }
app> db.log.find() //查詢全部記錄
注:默認每頁顯示20條記錄,當顯示不下的的狀況下,可使用it迭代命令查詢下一頁數據。
設置每頁顯示數據的大小:
> DBQuery.shellBatchSize=50; //每頁顯示50條記錄
50
app> db.log.findOne() //查看第1條記錄
app> db.log.count() //查詢總的記錄數量
app> db.log.remove({}) //刪除集合中全部記錄
> db.log.distinct("name") //查詢去掉當前集合中某列的重複數據:按照給定的條件除重查詢
[ "mm" ]
> db.yt.find()
{ "_id" : ObjectId("5b8763af7fdaa92f03ac0282"), "uid" : 3, "name" : "mongodb", "age" : 6, "date" : ISODate("2018-08-30T03:25:35.855Z") }
{ "_id" : ObjectId("5b8788577fdaa92f03ac0289"), "uid" : 2, "name" : "mongodb", "age" : 6, "date" : ISODate("2018-08-30T03:25:35.855Z") }
> db.yt.distinct('name')
[ "mongodb" ]
> db.yt.find()
{ "_id" : ObjectId("5b8763af7fdaa92f03ac0282"), "uid" : 3, "name" : "mongodb", "age" : 6, "date" : ISODate("2018-08-30T03:25:35.855Z") }
{ "_id" : ObjectId("5b8788577fdaa92f03ac0289"), "uid" : 2, "name" : "mongodb", "age" : 6, "date" : ISODate("2018-08-30T03:25:35.855Z") }
執行計劃(使用explain)
> db.students.find().explain()
{
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 1,
"nscannedObjects" : 1,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,
"nscannedAllPlans" : 1,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"server" : "SYNC-1:27017",
"filterSet" : false
}
注:
"cursor":BasicCursor表示沒有使用索引,BtreeCursor表示使用了索引。
"n":表示返回的文檔數量。
"nscanned":表示查詢了多少個文檔。
"millis":耗時(毫秒)。
"indexBounds":所用的索引。
app> db.log.stats()
app> db.log.dataSize() //集合中數據的原始大小
app> db.log.totalIndexSize() //集合中索引數據的原始大小
app> db.log.totalSize() //集合中索引+數據壓縮存儲以後的大小
app> db.log.storageSize() //集合中數據壓縮存儲的大小
MongoDB數據庫默認是沒有用戶名及密碼的,即無權限訪問限制。爲了方便數據庫的管理和安全,需建立數據庫用戶
----- admin數據庫 建立超級管理員,管理全部數據庫
語法含義:
user字段:用戶的名字;
pwd字段:用戶的密碼;
cusomData字段:爲任意內容,例如能夠爲用戶全名介紹;
roles字段:指定用戶的角色,能夠用一個空數組給新用戶設定空角色; roles 字段,能夠指定內置角色和用戶定義的角色。
###經常使用角色說明見官方文檔 https://docs.mongodb.com/manual/reference/built-in-roles/
注意: 刪除超級管理員也要刪除後修改配置再重啓
[root@wu ~]# mongo
use admin
db.createUser(
{
user: "root",
pwd: "root",
roles: [ { role: "root", db: "admin" } ]
}
)
注: 用戶建立完成後需在配置文件打開auth驗證並重啓後生效
> db.auth("root","root")
1
vi mongodb.conf
auth=true
[root@wu ~]# mongo -uroot -proot
MongoDB shell version: 3.2.8
connecting to: test
2018-08-31T15:09:19.992+0800 E QUERY [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow@src/mongo/shell/db.js:1441:20
@(auth):6:1
@(auth):1:2
exception: login failed
[root@wu ~]# mongo -uroot -proot admin
MongoDB shell version: 3.2.8
connecting to: admin
Server has startup warnings:
2018-08-30T17:41:51.606+0800 I CONTROL [initandlisten]
2018-08-30T17:41:51.606+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
>
[root@wu ~]# mongo -uroot admin -p
MongoDB shell version: 3.2.8
Enter password:
connecting to: admin
Server has startup warnings:
2018-08-30T17:41:51.606+0800 I CONTROL [initandlisten]
2018-08-30T17:41:51.606+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
> exit
bye
[root@wu ~]# mongo -uroot -p --authenticationDatabase admin 或者-p放後面 mongo -uroot --authenticationDatabase admin -p
MongoDB shell version: 3.2.8
Enter password:
connecting to: test
Server has startup warnings:
2018-08-30T17:41:51.606+0800 I CONTROL [initandlisten]
2018-08-30T17:41:51.606+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
>
--test
use test
db.createUser(
{
user: "test",
pwd: "test",
roles: [ { role: "read", db: "test" } ]
}
)
db.auth("test","test")
登陸test用戶,並測試
db.createCollection('b')
或者
> use app
switched to db app
> db.createUser(
... {
... user: "app02",
... pwd: "app02",
... roles: [ "read" ] ####這裏也能夠readWrite 讀寫權限
... }
... )
Successfully added user: { "user" : "app02", "roles" : [ "read" ] }
db.createUser(
{
user: "test1",
pwd: "test1",
roles: [ { role: "readWrite", db: "test" } ]
}
)
db.auth("test1","test1")
use app
db.createUser(
{
user: "app03",
pwd: "app03",
roles: [ { role: "readWrite", db: "app" },
{ role: "read", db: "test" }
]
}
)
db.auth("app03","app03")
mongo -uapp03 -papp03 app ###登陸命令, 下面是錯誤命令
[root@wu ~]# mongo -uapp03 -papp03
connecting to: test
2018-08-31T19:39:26.712+0800 E QUERY [thread1] Error: Authentication failed. :
exception: login failed
[root@wu ~]# mongo -uapp03 -papp03 test
connecting to: test
2018-08-31T19:41:25.217+0800 E QUERY [thread1] Error: Authentication failed. :
exception: login failed
這個管理員應該是不能建立和刪除用戶
先用root用戶登陸到admin數據庫,再進入到對應的庫
> use app
switched to db app
> db.createUser(
... {user:"appadmin",pwd:"appadmin",
... roles:[{role:"dbAdmin",db:"app"}]})
Successfully added user: {
"user" : "appadmin",
"roles" : [
{
"role" : "dbAdmin",
"db" : "app"
}
]
}
> db.auth("appadmin","appadmin")
刪除app01用戶:先登陸到admin數據庫
# mongo -uroot –proot 192.168.1.24/admin
use app
db.dropUser("app01")
只能是root用戶,而且進入到用戶所對應的庫裏才能刪除用戶
> use admin
switched to db admin
> db.dropUser("test")
false
> use test
switched to db test
> db.dropUser("test")
true
use app
db.createUser(
{
user: "app04",
pwd: "app04",
roles: [ { role: "readWrite", db: "app" },
{ role: "clusterAdmin", db: "admin" }
]
}
)
> db.test111.find()
{ "_id" : ObjectId("5b9767eb495282f21844e4cd"), "uid" : 0, "name" : "mongodb", "age" : 0, "date" : ISODate("2018-09-11T06:59:55.531Z") }
{ "_id" : ObjectId("5b9767eb495282f21844e4cf"), "uid" : 2, "name" : "mongodb", "age" : 2, "date" : ISODate("2018-09-11T06:59:55.533Z") }
{ "_id" : ObjectId("5b9767eb495282f21844e4d0"), "uid" : 3, "name" : "mongodb", "age" : 3, "date" : ISODate("2018-09-11T06:59:55.533Z") }
> db.test111.update( {uid: 2}, {$set : {age: 222}} )
> db.test111.find()
{ "_id" : ObjectId("5b9767eb495282f21844e4cd"), "uid" : 0, "name" : "mongodb", "age" : 0, "date" : ISODate("2018-09-11T06:59:55.531Z") }
{ "_id" : ObjectId("5b9767eb495282f21844e4cf"), "uid" : 2, "name" : "mongodb", "age" : 222, "date" : ISODate("2018-09-11T06:59:55.533Z") }
{ "_id" : ObjectId("5b9767eb495282f21844e4d0"), "uid" : 3, "name" : "mongodb", "age" : 3, "date" : ISODate("2018-09-11T06:59:55.533Z") }
一、apache+mysql+php都在一臺機器上
|||
這種架構的問題?
安全、性能、可擴展性?
二、apache+php, Mysql單獨存放
| -----------------------
| |
|
------------ ------------------------
三、 lvs\haproxy\keepalive 主從複製----》MHA+KA xxproxy
-----------------------------
一、apache+mongodb+php都在一臺機器上
二、apache+php, mongodb單獨存放
----------------------- -----------------------
| |
| |
| |
-----------------------------------------------------------
RS複製集:
一、故障轉移 ------》內部心跳,投票機制{一、狀態偵測,二、選主切換}
二、應用鏈接的問題 ---》客戶端驅動
分擔負載:
sharding技術
raft
使得多個進程或服務器在某方面保持相同
必須處理一系列大範圍的故障節點
磁盤故障( disk failure)
網絡分區( network partitions)
機器凍結( machine freezes )
時鐘脈衝相位差( clock skews )
mongodb 3.2的改進:
目標及raft一致性算法的啓發
避免二次投票
監控節點狀態
申請選舉
Raft概念
術語(選舉)
使用現有數據複製集渠道監控節點狀態
非對稱的選舉超時
一組Mongodb複製集,就是一組mongod進程,這些進程維護同一個數據集合。複製集提供了數據冗餘和高等級的可靠性,這是生產部署的基礎。
保證數據在生產部署時的冗餘和可靠性,經過在不一樣的機器上保存副原本保證數據的不會由於單點損壞而丟失。可以隨時應對數據丟失、機器損壞帶來的風險,牛逼到不行。
換一句話來講,還能提升讀取能力,用戶的讀取服務器和寫入服務器在不一樣的地方,並且,由不一樣的服務器爲不一樣的用戶提供服務,提升整個系統的負載,簡直就是雲存儲的翻版...
一組複製集就是一組mongod實例掌管同一個數據集,實例能夠在不一樣的機器上面。實例中包含一個主導,接受客戶端全部的寫入操做,其餘都是副本實例,從主服務器上得到數據並保持同步。
主服務器很重要,包含了全部的改變操做(寫)的日誌。可是副本服務器集羣包含有全部的主服務器數據,所以當主服務器掛掉了,就會在副本服務器上從新選取一個成爲主服務器。
每一個複製集還有一個仲裁者,仲裁者不存儲數據,只是負責經過心跳包來確認集羣中集合的數量,並在主服務器選舉的時候做爲仲裁決定結果。
MongoDB的單實例模式下,一個mongod進程爲一個實例,一個實例中包含若干db,每一個db包含若干張表。
MongoDB經過一張特殊的表local.oplog.rs存儲oplog,該表的特色是:固定大小,滿了會刪除最舊記錄插入新記錄,並且只支持append操做,所以能夠理解爲一個持久化的ring-buffer。oplog是MongoDB複製集的核心功能點。
MongoDB複製集是指MongoDB實例經過複製並應用其餘實例的oplog達到數據冗餘的技術。
一個包含3個mongod的複製集架構以下所示
若是主服務器失效, 會變成:
若是加上可選的仲裁者:
此時主服務器失效:
客戶端將不會把讀請求分發到隱藏節點上,即便咱們設定了 複製集讀選項 。這些隱藏節點將不會收到來自應用程序的請求。咱們能夠將隱藏節點專用於報表節點或是備份節點。 延時節點也應該是一個隱藏節點。
延時節點的數據集是延時的,所以它能夠幫助咱們在人爲誤操做或是其餘意外狀況下恢復數據。舉個例子,當應用升級失敗,或是誤操做刪除了表和數據庫時,咱們能夠經過延時節點進行數據恢復。
{
"_id" : <num>, "host" : <hostname:port>,
"priority" : 0,
"slaveDelay" : <seconds>, "hidden" : true
}
搭建三節點MongoDB複製集
一、準備三套MongoDB數據庫(能夠多臺,單臺能夠多實例)
二、配置複製集
三、測試複製集
四、模擬故障切換
準備三臺機器,分別搭建mongod單實例.
1臺機器3個實例,不一樣的目錄結構(dbpath、logpath、conf【不一樣的conf文件】),不一樣的端口號
-----配置準備----規劃:
實例一:
port:27017
/mongodb/data/db17
/mongodb/log/db17.log
/mongodb/conf/db17.conf
實例二:
port:27018
/mongodb/data/db18
/mongodb/log/db18.log
/mongodb/conf/db18.conf
實例三:
port:27019
/mongodb/data/db19
/mongodb/log/db19.log
/mongodb/conf/db19.conf
(建立所需目錄和文件)##注意文件的屬主得是mongod
[mongod@web01 ~]$ mkdir /mongodb/data/db17
[mongod@web01 ~]$ mkdir /mongodb/data/db18
[mongod@web01 ~]$ mkdir /mongodb/data/db19
[mongod@web01 ~]$ touch /mongodb/conf/db17.conf
[mongod@web01 ~]$ touch /mongodb/conf/db18.conf
[mongod@web01 ~]$ touch /mongodb/conf/db19.conf
(修改各個實例配置文件)
vi /mongodb/conf/db17.conf ---------->/mongodb/conf/db18.conf,/mongodb/conf/db19.conf
systemLog:
destination: file
path: /mongodb/log/db17.log ------>18,19
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db17 -------->18,19
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
processManagement:
fork: true
net:
port: 27017 ------>27018,27019
replication:
oplogSizeMB: 2048
replSetName: my_repl
vi /mongodb/conf/db18.conf
dbpath=/mongodb/data/db18
port=27018
logpath=/mongodb/log/db18.log
fork=true
logappend=true
vi /mongodb/conf/db19.conf
dbpath=/mongodb/data/db19
port=27019
logpath=/mongodb/log/db19.log
fork=true
logappend=true
######################問題###由於剛纔用簡單的配置文件啓動了,如今啓動不了, 無數據的環境直接刪除數據文件新建
[mongodb@wu ~]$ mongod -f /mongodb/conf/db7.conf
about to fork child process, waiting until server is ready for connections.
forked process: 13692
ERROR: child process failed, exited with error number 100
[mongodb@wu ~]$ logout
[root@wu ~]# cd /mongodb/data/
[root@wu data]# rm -rf db7 db8 db9
[root@wu data]# mkdir db7 db8 db9
[root@wu mongodb]# chown -R mongodb.mongodb .
[mongod@web01 ~]$ mongod -f /mongodb/conf/db17.conf
about to fork child process, waiting until server is ready for connections.
forked process: 1754
child process started successfully, parent exiting
[mongod@web01 ~]$ mongod -f /mongodb/conf/db18.conf
about to fork child process, waiting until server is ready for connections.
forked process: 1772
child process started successfully, parent exiting
[mongod@web01 ~]$ mongod -f /mongodb/conf/db19.conf
about to fork child process, waiting until server is ready for connections.
forked process: 1790
child process started successfully, parent exiting
[mongod@web01 ~]$ ps aux|grep mongo
mongo --port=27017
use admin
config = {_id: 'my_repl', members: [
{_id: 0, host: '10.0.0.8:27017'},
{_id: 1, host: '10.0.0.8:27018'},
{_id: 2, host: '10.0.0.8:27019',}]
}
config = {_id: 'my_repl', members: [
{_id: 0, host: '10.0.0.8:27017'},
{_id: 1, host: '10.0.0.8:27018'},
{_id: 2, host: '10.0.0.8:27019',"arbiterOnly":true}]
}
config = {_id: 'my_repl', members: [
{_id: 0, host: '10.0.0.8:27017'},
{_id: 1, host: '10.0.0.8:27018'},
{_id: 2, host: '10.0.0.8:27019',hidden : true,priority : 0,slaveDelay : NumberLong(120)}]
}
rs.initiate(config)
[root@wu data]# mongo --port 27017
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27017/test
Server has startup warnings:
2018-09-03T14:20:03.124+0800 I CONTROL [initandlisten]
2018-09-03T14:20:03.124+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
> config = {_id: 'my_repl', members: [
... {_id: 0, host: '10.0.0.10:27017'},
... {_id: 1, host: '10.0.0.10:27018'},
... {_id: 2, host: '10.0.0.10:27019'},
... ]}
{
"_id" : "my_repl",
"members" : [
{
"_id" : 0,
"host" : "10.0.0.10:27017"
},
{
"_id" : 1,
"host" : "10.0.0.10:27018"
},
{
"_id" : 2,
"host" : "10.0.0.10:27019"
}
]
}
> rs.initiate(config)
{ "ok" : 1 }
my_repl:OTHER> exit
bye
[root@wu data]# mongo --port 27017
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27017/test
Server has startup warnings:
2018-09-03T14:20:03.124+0800 I CONTROL [initandlisten]
2018-09-03T14:20:03.124+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:PRIMARY> exit
bye
[root@wu data]# mongo --port 27018
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27018/test
Server has startup warnings:
2018-09-03T10:22:17.049+0800 I CONTROL [initandlisten]
2018-09-03T10:22:17.049+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:SECONDARY> exit
bye
[root@wu data]# mongo --port 27019
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27019/test
Server has startup warnings:
2018-09-03T10:31:36.047+0800 I CONTROL [initandlisten]
2018-09-03T10:31:36.047+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:SECONDARY> exit
bye
[root@wu data]#
在主節點插入數據,去從節點驗證
[mongod@web01 data]$ mongo --port=27017
use app
db.movies.insert([ { "title" : "Jaws", "year" : 1975, "imdb_rating" : 8.1 },
... { "title" : "Batman", "year" : 1989, "imdb_rating" : 7.6 },
... ] )
[root@wu data]# mongo --port 27017
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27017/test
Server has startup warnings:
2018-09-03T14:20:03.124+0800 I CONTROL [initandlisten]
2018-09-03T14:20:03.124+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:PRIMARY> use app
switched to db app
my_repl:PRIMARY> db.movies.insert([ { "title" : "Jaws", "year" : 1975, "imdb_rating" : 8.1 },
... ... { "title" : "Batman", "year" : 1989, "imdb_rating" : 7.6 },
... ... ] )
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
my_repl:PRIMARY> show tables
movies
my_repl:PRIMARY> db.movies.find()
{ "_id" : ObjectId("5b8cd819e4bddfd9f8c86383"), "title" : "Jaws", "year" : 1975, "imdb_rating" : 8.1 }
{ "_id" : ObjectId("5b8cd819e4bddfd9f8c86384"), "title" : "Batman", "year" : 1989, "imdb_rating" : 7.6 }
my_repl:PRIMARY> db.movies.find().pretty();
{
"_id" : ObjectId("5b8cd819e4bddfd9f8c86383"),
"title" : "Jaws",
"year" : 1975,
"imdb_rating" : 8.1
}
{
"_id" : ObjectId("5b8cd819e4bddfd9f8c86384"),
"title" : "Batman",
"year" : 1989,
"imdb_rating" : 7.6
}
my_repl:PRIMARY>
[mongod@web01 data]$ mongo --port=27018
use app
my_repl:SECONDARY> db.movies.find(); ---->報錯?爲何? ↓↓↓
my_repl:SECONDARY> rs.slaveOk();
[mongodb@wu ~]$ mongo --port 27018
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27018/test
Server has startup warnings:
2018-09-03T10:22:17.049+0800 I CONTROL [initandlisten]
2018-09-03T10:22:17.049+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:SECONDARY> use app
switched to db app
my_repl:SECONDARY> show tables
2018-09-03T14:54:43.087+0800 E QUERY [thread1] Error: listCollections failed: { "ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435 } :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:773:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:785:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:796:16
shellHelper.show@src/mongo/shell/utils.js:754:9
shellHelper@src/mongo/shell/utils.js:651:15
@(shellhelp2):1:1
my_repl:SECONDARY> rs.slaveOk()
my_repl:SECONDARY> show tables
movies
my_repl:SECONDARY> db.movies.find()
{ "_id" : ObjectId("5b8cd819e4bddfd9f8c86383"), "title" : "Jaws", "year" : 1975, "imdb_rating" : 8.1 }
{ "_id" : ObjectId("5b8cd819e4bddfd9f8c86384"), "title" : "Batman", "year" : 1989, "imdb_rating" : 7.6 }
[root@wu ~]# mongo --port 27019
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27019/test
Server has startup warnings:
2018-09-03T10:31:36.047+0800 I CONTROL [initandlisten]
2018-09-03T10:31:36.047+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:SECONDARY> show dbs
2018-09-03T15:07:21.554+0800 E QUERY [thread1] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435 } :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:761:19
shellHelper@src/mongo/shell/utils.js:651:15
@(shellhelp2):1:1
my_repl:SECONDARY> rs.s
rs.slaveOk( rs.status( rs.stepDown( rs.syncFrom(
my_repl:SECONDARY> rs.slaveOk()
my_repl:SECONDARY> show dbs
app 0.000GB
local 0.000GB
my_repl:SECONDARY> use app
switched to db app
my_repl:SECONDARY> show tables
movies
my_repl:SECONDARY> db.movies.find()
{ "_id" : ObjectId("5b8cd819e4bddfd9f8c86383"), "title" : "Jaws", "year" : 1975, "imdb_rating" : 8.1 }
{ "_id" : ObjectId("5b8cd819e4bddfd9f8c86384"), "title" : "Batman", "year" : 1989, "imdb_rating" : 7.6 }
my_repl:SECONDARY>
rs.add("ip:port"); // 新增從節點
rs.addArb("ip:port"); // 新增仲裁節點
rs.remove("ip:port"); // 刪除一個節點
rs.isMaster(); // 查看當前是不是主節點
rs.addArb("10.0.0.8:27020");
--查看副本集的配置信息
admin> rs.config()
--查看副本集各成員的狀態
admin> rs.status()
--副本集角色切換
admin> rs.stepDown()
注:
admin> rs.freeze(300) //鎖定從,使其不會轉變成主庫
freeze()和stepDown單位都是秒。
--設置副本節點可讀:在副本節點執行
admin> rs.slaveOk()
eg:
admin> use app
switched to db app
app> db.createCollection('a')
{ "ok" : 0, "errmsg" : "not master", "code" : 10107 }
--查看副本節點
admin> rs.printSlaveReplicationInfo()
source: 192.168.1.22:27017
syncedTo: Thu May 26 2016 10:28:56 GMT+0800 (CST)
0 secs (0 hrs) behind the primary
[root@wu ~]# su - mongodb
[mongodb@wu ~]$ cd /mongodb/data/
[mongodb@wu data]$ mkdir db20
[mongodb@wu data]$ ll |grep ^d
drwxrwxr-x 2 mongodb mongodb 4096 Sep 3 15:38 db20
drwxr-xr-x 6 mongodb mongodb 4096 Sep 3 15:33 db7
drwxr-xr-x 6 mongodb mongodb 4096 Sep 3 15:33 db8
drwxr-xr-x 6 mongodb mongodb 4096 Sep 3 15:32 db9
drwxrwxr-x 2 mongodb mongodb 4096 Sep 3 09:20 diagnostic.data
drwxrwxr-x 2 mongodb mongodb 4096 Aug 31 18:11 journal
[mongodb@wu data]$ touch /mongodb/conf/db20.conf
[mongodb@wu data]$ cat /mongodb/conf/db7.conf >/mongodb/conf/db20.conf
[mongodb@wu data]$ vim /mongodb/conf/db20.conf
systemLog:
destination: file
path: /mongodb/log/db20.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db20
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
processManagement:
fork: true
net:
port: 27020
replication:
oplogSizeMB: 2048
replSetName: my_repl
~
"/mongodb/conf/db20.conf" 26L, 481C written
[mongodb@wu data]$ mongod -f /mongodb/conf/db20.conf
about to fork child process, waiting until server is ready for connections.
forked process: 14806
child process started successfully, parent exiting
[mongodb@wu data]$ netstat -lntp
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 14301/mongod
tcp 0 0 0.0.0.0:27018 0.0.0.0:* LISTEN 13775/mongod
tcp 0 0 0.0.0.0:27019 0.0.0.0:* LISTEN 13889/mongod
tcp 0 0 0.0.0.0:27020 0.0.0.0:* LISTEN 14806/mongod
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -
tcp 0 0 :::22 :::* LISTEN -
[mongodb@wu data]$
[mongodb@wu data]$ mongo --port=27020
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27020/test
> exit
bye
[mongodb@wu data]$ mongo --port=27017
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27017/test
Server has startup warnings:
2018-09-03T14:20:03.124+0800 I CONTROL [initandlisten]
2018-09-03T14:20:03.124+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:PRIMARY> use admin
switched to db admin
my_repl:PRIMARY> rs.add
rs.add( rs.addArb(
my_repl:PRIMARY> rs.addArb("10.0.0.10:27020")
{ "ok" : 1 }
my_repl:PRIMARY>
my_repl:PRIMARY> rs.status()
{
"set" : "my_repl",
"date" : ISODate("2018-09-03T07:46:39.238Z"),
"myState" : 1,
"term" : NumberLong(1),
"heartbeatIntervalMillis" : NumberLong(2000),
"members" : [
{
"_id" : 0,
"name" : "10.0.0.10:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 5196,
"optime" : {
"ts" : Timestamp(1535960682, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2018-09-03T07:44:42Z"),
"electionTime" : Timestamp(1535956326, 1),
"electionDate" : ISODate("2018-09-03T06:32:06Z"),
"configVersion" : 2,
"self" : true
},
{
"_id" : 1,
"name" : "10.0.0.10:27018",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 4484,
"optime" : {
"ts" : Timestamp(1535960682, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2018-09-03T07:44:42Z"),
"lastHeartbeat" : ISODate("2018-09-03T07:46:38.535Z"),
"lastHeartbeatRecv" : ISODate("2018-09-03T07:46:38.563Z"),
"pingMs" : NumberLong(0),
"syncingTo" : "10.0.0.10:27017",
"configVersion" : 2
},
{
"_id" : 2,
"name" : "10.0.0.10:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 4484,
"optime" : {
"ts" : Timestamp(1535960682, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2018-09-03T07:44:42Z"),
"lastHeartbeat" : ISODate("2018-09-03T07:46:38.535Z"),
"lastHeartbeatRecv" : ISODate("2018-09-03T07:46:38.553Z"),
"pingMs" : NumberLong(0),
"syncingTo" : "10.0.0.10:27017",
"configVersion" : 2
},
{
"_id" : 3,
"name" : "10.0.0.10:27020",
"health" : 1,
"state" : 7,
"stateStr" : "ARBITER",
"uptime" : 116,
"lastHeartbeat" : ISODate("2018-09-03T07:46:38.535Z"),
"lastHeartbeatRecv" : ISODate("2018-09-03T07:46:37.499Z"),
"pingMs" : NumberLong(0),
"configVersion" : 2
}
],
"ok" : 1
}
my_repl:PRIMARY>
my_repl:ARBITER> rs.isMaster()
{
"hosts" : [
"10.0.0.10:27017",
"10.0.0.10:27018",
"10.0.0.10:27019"
],
"arbiters" : [
"10.0.0.10:27020"
],
"setName" : "my_repl",
"setVersion" : 2,
"ismaster" : false,
"secondary" : false,
"primary" : "10.0.0.10:27017",
"arbiterOnly" : true,
"me" : "10.0.0.10:27020",
"maxBsonObjectSize" : 16777216,
"maxMessageSizeBytes" : 48000000,
"maxWriteBatchSize" : 1000,
"localTime" : ISODate("2018-09-03T10:32:23.466Z"),
"maxWireVersion" : 4,
"minWireVersion" : 0,
"ok" : 1
}
格式:
cfg=rs.conf() /*找到須要改成延遲性同步的數組號*/;
cfg.members[N].priority=0
cfg.members[N].slaveDelay=120
cfg.members[N].hidden=true
rs.reconfig(cfg)
實驗:
cfg=rs.conf()
cfg.members[2].priority=0
cfg.members[2].slaveDelay=120
cfg.members[2].hidden=true
rs.reconfig(cfg)
[root@wu data]# mongo --port 27017
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27017/test
my_repl:PRIMARY> cfg=rs.conf()
{
"_id" : "my_repl",
"version" : 2,
"protocolVersion" : NumberLong(1),
"members" : [
{
"_id" : 0,
"host" : "10.0.0.10:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "10.0.0.10:27018",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "10.0.0.10:27019",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 3,
"host" : "10.0.0.10:27020",
"arbiterOnly" : true,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"getLastErrorModes" : {
},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5b8cd55a8425ac85a30e09aa")
}
}
my_repl:PRIMARY> cfg.members[2].priority=0
0
my_repl:PRIMARY> cfg.members[2].slaveDelay=120
120
my_repl:PRIMARY> cfg.members[2].hidden=true
true
my_repl:PRIMARY> rs.reconfig(cfg)
{ "ok" : 1 }
my_repl:PRIMARY> cfg=rs.conf()
{
"_id" : "my_repl",
"version" : 3,
"protocolVersion" : NumberLong(1),
"members" : [
{
"_id" : 0,
"host" : "10.0.0.10:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "10.0.0.10:27018",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "10.0.0.10:27019",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : true,
"priority" : 0,
"tags" : {
},
"slaveDelay" : NumberLong(120),
"votes" : 1
},
{
"_id" : 3,
"host" : "10.0.0.10:27020",
"arbiterOnly" : true,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"getLastErrorModes" : {
},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5b8cd55a8425ac85a30e09aa")
}
}
my_repl:ARBITER> rs.conf()
{
"_id" : "my_repl",
"version" : 3,
"protocolVersion" : NumberLong(1),
"members" : [
{
"_id" : 0,
"host" : "10.0.0.10:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "10.0.0.10:27018",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "10.0.0.10:27019",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : true,
"priority" : 0,
"tags" : {
},
"slaveDelay" : NumberLong(120),
"votes" : 1
},
{
"_id" : 3,
"host" : "10.0.0.10:27020",
"arbiterOnly" : true,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"getLastErrorModes" : {
},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5b8cd55a8425ac85a30e09aa")
}
}
my_repl:ARBITER>
my_repl:PRIMARY> rs.status() ####如今是27017實例
{
"set" : "my_repl",
"date" : ISODate("2018-09-03T10:50:10.261Z"),
"myState" : 1,
"term" : NumberLong(1),
"heartbeatIntervalMillis" : NumberLong(2000),
"members" : [
{
"_id" : 0,
"name" : "10.0.0.10:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 16207,
"optime" : {
"ts" : Timestamp(1535971765, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2018-09-03T10:49:25Z"),
"electionTime" : Timestamp(1535956326, 1),
"electionDate" : ISODate("2018-09-03T06:32:06Z"),
"configVersion" : 3,
"self" : true
},
{
"_id" : 1,
"name" : "10.0.0.10:27018",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 15495,
"optime" : {
"ts" : Timestamp(1535971765, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2018-09-03T10:49:25Z"),
"lastHeartbeat" : ISODate("2018-09-03T10:50:09.653Z"),
"lastHeartbeatRecv" : ISODate("2018-09-03T10:50:09.651Z"),
"pingMs" : NumberLong(0),
"syncingTo" : "10.0.0.10:27017",
"configVersion" : 3
},
{
"_id" : 2,
"name" : "10.0.0.10:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 15495,
"optime" : {
"ts" : Timestamp(1535971765, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2018-09-03T10:49:25Z"),
"lastHeartbeat" : ISODate("2018-09-03T10:50:09.653Z"),
"lastHeartbeatRecv" : ISODate("2018-09-03T10:50:09.653Z"),
"pingMs" : NumberLong(0),
"syncingTo" : "10.0.0.10:27017",
"configVersion" : 3
},
{
"_id" : 3,
"name" : "10.0.0.10:27020",
"health" : 1,
"state" : 7,
"stateStr" : "ARBITER",
"uptime" : 11127,
"lastHeartbeat" : ISODate("2018-09-03T10:50:09.651Z"),
"lastHeartbeatRecv" : ISODate("2018-09-03T10:50:05.568Z"),
"pingMs" : NumberLong(0),
"configVersion" : 3
}
],
"ok" : 1
}
my_repl:PRIMARY>
my_repl:PRIMARY> rs.isMaster()
{
"hosts" : [
"10.0.0.10:27017",
"10.0.0.10:27018"
],
"arbiters" : [
"10.0.0.10:27020"
],
"setName" : "my_repl",
"setVersion" : 3,
"ismaster" : true,
"secondary" : false,
"primary" : "10.0.0.10:27017",
"me" : "10.0.0.10:27017",
"electionId" : ObjectId("7fffffff0000000000000001"),
"maxBsonObjectSize" : 16777216,
"maxMessageSizeBytes" : 48000000,
"maxWriteBatchSize" : 1000,
"localTime" : ISODate("2018-09-05T01:33:29.062Z"),
"maxWireVersion" : 4,
"minWireVersion" : 0,
"ok" : 1
}
my_repl:PRIMARY> exit
bye
[root@wu data]# ps aux|grep mongo
root 13730 0.0 0.0 163408 1976 pts/1 S Sep03 0:00 su - mongodb
mongodb 13731 0.0 0.0 108360 1824 pts/1 S Sep03 0:00 -bash
mongodb 13775 0.6 2.6 890420 54304 ? Sl Sep03 17:28 mongod -f /mongodb/conf/db8.conf
mongodb 13889 0.6 2.6 887360 53848 ? Sl Sep03 17:24 /mongodb/bin/mongod -f /mongodb/conf/db9.conf
mongodb 14301 0.6 2.5 904916 51320 ? Sl Sep03 17:25 /mongodb/bin/mongod -f /mongodb/conf/db7.conf
root 14771 0.0 0.0 163408 1976 pts/2 S Sep03 0:00 su - mongodb
mongodb 14772 0.0 0.0 108360 1836 pts/2 S Sep03 0:00 -bash
mongodb 14806 0.4 2.4 466640 49644 ? Sl Sep03 10:57 mongod -f /mongodb/conf/db20.conf
mongodb 14874 0.0 0.9 193092 18664 pts/2 Sl+ Sep03 0:00 mongo --port=27020
mongodb 15079 0.0 0.8 192000 18016 pts/1 Sl+ Sep03 0:00 mongo --port 27018
root 18423 0.0 0.0 103332 836 pts/0 S+ 09:34 0:00 grep mongo
[root@wu data]#
[root@wu data]# kill -2 14301
[root@wu data]# ps aux|grep mongo
root 13730 0.0 0.0 163408 1976 pts/1 S Sep03 0:00 su - mongodb
mongodb 13731 0.0 0.0 108360 1824 pts/1 S Sep03 0:00 -bash
mongodb 13775 0.6 2.6 890420 54368 ? Sl Sep03 17:29 mongod -f /mongodb/conf/db8.conf
mongodb 13889 0.6 2.6 887360 53900 ? Sl Sep03 17:24 /mongodb/bin/mongod -f /mongodb/conf/db9.conf
root 14771 0.0 0.0 163408 1976 pts/2 S Sep03 0:00 su - mongodb
mongodb 14772 0.0 0.0 108360 1836 pts/2 S Sep03 0:00 -bash
mongodb 14806 0.4 2.4 466640 49660 ? Sl Sep03 10:57 mongod -f /mongodb/conf/db20.conf
mongodb 14874 0.0 0.9 193092 18664 pts/2 Sl+ Sep03 0:00 mongo --port=27020
mongodb 15079 0.0 0.8 192000 18016 pts/1 Sl+ Sep03 0:00 mongo --port 27018
root 18431 0.0 0.0 103332 840 pts/0 S+ 09:35 0:00 grep mongo
[root@wu data]# mongo --port 27018
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27018/test
Server has startup warnings:
2018-09-03T10:22:17.049+0800 I CONTROL [initandlisten]
2018-09-03T10:22:17.049+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:PRIMARY> rs.isMaster()
{
"hosts" : [
"10.0.0.10:27017",
"10.0.0.10:27018"
],
"arbiters" : [
"10.0.0.10:27020"
],
"setName" : "my_repl",
"setVersion" : 3,
"ismaster" : true,
"secondary" : false,
"primary" : "10.0.0.10:27018",
"me" : "10.0.0.10:27018",
"electionId" : ObjectId("7fffffff0000000000000002"),
"maxBsonObjectSize" : 16777216,
"maxMessageSizeBytes" : 48000000,
"maxWriteBatchSize" : 1000,
"localTime" : ISODate("2018-09-05T01:35:35.920Z"),
"maxWireVersion" : 4,
"minWireVersion" : 0,
"ok" : 1
}
my_repl:PRIMARY> rs.status()
{
"set" : "my_repl",
"date" : ISODate("2018-09-05T01:35:58.868Z"),
"myState" : 1,
"term" : NumberLong(2),
"heartbeatIntervalMillis" : NumberLong(2000),
"members" : [
{
"_id" : 0,
"name" : "10.0.0.10:27017",
"health" : 0,
"state" : 8,
"stateStr" : "(not reachable/healthy)",
"uptime" : 0,
"optime" : {
"ts" : Timestamp(0, 0),
"t" : NumberLong(-1)
},
"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
"lastHeartbeat" : ISODate("2018-09-05T01:35:57.617Z"),
"lastHeartbeatRecv" : ISODate("2018-09-05T01:34:58.517Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "Connection refused",
"configVersion" : -1
},
{
"_id" : 1,
"name" : "10.0.0.10:27018",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 170022,
"optime" : {
"ts" : Timestamp(1536111310, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2018-09-05T01:35:10Z"),
"infoMessage" : "could not find member to sync from",
"electionTime" : Timestamp(1536111309, 1),
"electionDate" : ISODate("2018-09-05T01:35:09Z"),
"configVersion" : 3,
"self" : true
},
{
"_id" : 2,
"name" : "10.0.0.10:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 155041,
"optime" : {
"ts" : Timestamp(1535971765, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2018-09-03T10:49:25Z"),
"lastHeartbeat" : ISODate("2018-09-05T01:35:57.617Z"),
"lastHeartbeatRecv" : ISODate("2018-09-05T01:35:58.393Z"),
"pingMs" : NumberLong(0),
"syncingTo" : "10.0.0.10:27018",
"configVersion" : 3
},
{
"_id" : 3,
"name" : "10.0.0.10:27020",
"health" : 1,
"state" : 7,
"stateStr" : "ARBITER",
"uptime" : 150676,
"lastHeartbeat" : ISODate("2018-09-05T01:35:57.601Z"),
"lastHeartbeatRecv" : ISODate("2018-09-05T01:35:54.477Z"),
"pingMs" : NumberLong(0),
"configVersion" : 3
}
],
"ok" : 1
}
my_repl:PRIMARY>
[mongodb@wu ~]$ mongod -f /mongodb/conf/db7.conf
about to fork child process, waiting until server is ready for connections.
forked process: 18454
child process started successfully, parent exiting
[mongodb@wu ~]$ mongo --port 27018
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27018/test
Server has startup warnings:
2018-09-03T10:22:17.049+0800 I CONTROL [initandlisten]
2018-09-03T10:22:17.049+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
my_repl:PRIMARY> rs.isMaster()
{
"hosts" : [
"10.0.0.10:27017",
"10.0.0.10:27018"
],
"arbiters" : [
"10.0.0.10:27020"
],
"setName" : "my_repl",
"setVersion" : 3,
"ismaster" : true,
"secondary" : false,
"primary" : "10.0.0.10:27018",
"me" : "10.0.0.10:27018",
"electionId" : ObjectId("7fffffff0000000000000002"),
"maxBsonObjectSize" : 16777216,
"maxMessageSizeBytes" : 48000000,
"maxWriteBatchSize" : 1000,
"localTime" : ISODate("2018-09-05T01:46:33.963Z"),
"maxWireVersion" : 4,
"minWireVersion" : 0,
"ok" : 1
}
my_repl:PRIMARY> rs.status()
{
"set" : "my_repl",
"date" : ISODate("2018-09-05T01:47:08.547Z"),
"myState" : 1,
"term" : NumberLong(2),
"heartbeatIntervalMillis" : NumberLong(2000),
"members" : [
{
"_id" : 0,
"name" : "10.0.0.10:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 106,
"optime" : {
"ts" : Timestamp(1536111310, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2018-09-05T01:35:10Z"),
"lastHeartbeat" : ISODate("2018-09-05T01:47:08.096Z"),
"lastHeartbeatRecv" : ISODate("2018-09-05T01:47:08.057Z"),
"pingMs" : NumberLong(0),
"syncingTo" : "10.0.0.10:27018",
"configVersion" : 3
},
{
"_id" : 1,
"name" : "10.0.0.10:27018",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 170692,
"optime" : {
"ts" : Timestamp(1536111310, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2018-09-05T01:35:10Z"),
"electionTime" : Timestamp(1536111309, 1),
"electionDate" : ISODate("2018-09-05T01:35:09Z"),
"configVersion" : 3,
"self" : true
},
{
"_id" : 2,
"name" : "10.0.0.10:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 155711,
"optime" : {
"ts" : Timestamp(1536111310, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2018-09-05T01:35:10Z"),
"lastHeartbeat" : ISODate("2018-09-05T01:47:08.011Z"),
"lastHeartbeatRecv" : ISODate("2018-09-05T01:47:06.750Z"),
"pingMs" : NumberLong(0),
"syncingTo" : "10.0.0.10:27018",
"configVersion" : 3
},
{
"_id" : 3,
"name" : "10.0.0.10:27020",
"health" : 1,
"state" : 7,
"stateStr" : "ARBITER",
"uptime" : 151346,
"lastHeartbeat" : ISODate("2018-09-05T01:47:07.951Z"),
"lastHeartbeatRecv" : ISODate("2018-09-05T01:47:04.648Z"),
"pingMs" : NumberLong(0),
"configVersion" : 3
}
],
"ok" : 1
}
my_repl:PRIMARY>
mgdb水平擴展使用了分片技術, 有點相似mysql裏的分庫分表.
高數據量和吞吐量的數據庫應用會對單機的性能形成較大壓力,大的查詢量會將單機的CPU耗盡,大的數據量對單機的存儲壓力較大,最終會耗盡系統的內存而將壓力轉移到磁盤IO上。爲了解決這些問題,有兩個基本的方法: 垂直擴展和水平擴展。
垂直擴展:增長更多的CPU和存儲資源來擴展容量。
水平擴展:將數據集分佈在多個服務器上。水平擴展即分片。
Config Server
存儲集羣全部節點、分片數據路由信息。默認須要配置3個Config Server節點。
Mongos
提供對外應用訪問,全部操做均經過mongos執行。通常有多個mongos節點。數據遷移和數據自動平衡。
Mongod
存儲應用數據記錄。通常有多個Mongod節點,達到數據分片目的。
初始1個chunk
缺省chunk 大小:64MB
MongoDB自動拆分& 遷移chunks
適合業務的chunksize是最好的。
chunk的分裂和遷移:很是消耗IO資源。
chunk分裂的時機:插入和更新,讀數據不會分裂。
chunksize的選擇:
> 小的chunksize:數據均衡是遷移速度快,數據分佈更均勻。數據分裂頻繁,路由節點消耗更多資源。
> 大的chunksize:數據分裂少。數據塊移動集中消耗IO資源。
一般100-200M
當數據寫入時,MongoDB Cluster根據分片鍵設計寫入數據。
當外部語句發起數據查詢時,MongoDB根據數據分佈自動路由至指定節點返回數據。
Sharded Cluster支持將單個集合的數據分散存儲在多shard上,用戶能夠指定根據集合內文檔的某個字段即shard key來分佈數據。
範圍分片:
如圖,第一個chunk的範圍就是uid從-∞到12000範圍內的數據。第二個就是12000到58000 。以此類推。對於一個剛配置爲Sharding的collection ,最開始只有一個chunk,範圍是從-∞到+∞。
隨着數據的增加,其中的數據大小超過了配置的chunk size,默認是64M,則這個chunk就會分裂成兩個。數據的增加會讓chunk分裂得愈來愈多。這時候,各個shard 上的chunk數量就會不平衡。這時候,mongos中的一個組件balancer就會執行自動平衡。把chunk從chunk數量最多的shard節點挪動到數量最少的節點。
Hash分片與範圍分片互補,能將文檔隨機的分散到各個chunk,充分的擴展寫能力,彌補了範圍分片的不足,但不能高效的服務範圍查詢,全部的範圍查詢要分發到後端全部的Shard才能找出知足條件的文檔。
必須爲分片collection 定義分片鍵。
基於一個或多個列(相似一個索引)。
分片鍵定義數據空間。
想象key space 相似一條線上一個點數據。
一個key range 是一條線上一段數據。
分片鍵是不可變。
分片鍵必須有索引。
分片鍵大小限制512bytes。
分片鍵用於路由查詢。
MongoDB不接受已進行collection級分片的collection上插入無分片鍵的文檔(也不支持空值插入)
遞增的sharding key
數據文件挪動小。(優點)
由於數據文件遞增,因此會把insert的寫IO永久放在最後一片上,形成最後一片的寫熱點。
同時,隨着最後一片的數據量增大,將不斷的發生遷移至以前的片上。
隨機的sharding key
數據分佈均勻,insert的寫IO均勻分佈在多個片上。(優點)
大量的隨機IO,磁盤不堪重荷。
混合型key
大方向隨機遞增。
小範圍隨機分佈。
注: 能夠參考shard+rs.txt 文檔
性能問題
sharding集羣=shrd+RS
mongos: 接收請求,響應請求,請求config
config server : 元數據,分片的位置、分片的策略、分片節點信息、chunk位置信息
shard節點: 真實數據
-----------------
準備10個mongod實例
端口:27030-27039
目錄規劃:
mkdir /mongodb/data/db{30..39}
touch /mongodb/conf/db{30..39}.conf
[mongodb@wu data]$ mkdir /mongodb/data/db{30..39}
[mongodb@wu data]$ ll |grep ^d
[mongodb@wu data]$ touch /mongodb/conf/db{30..39}.conf
角色規劃:
configserver RS: db30->db32
mongos : db33
shard節點:
shard1 RS:
db34\db35\db36
shard2 RS:
db37\db38\db39
---------------------------------
vi /mongodb/conf/db30.conf
systemLog:
destination: file
path: /mongodb/log/db30.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db30
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
##bindIp:10.0.0.10
port: 27030
replication:
oplogSizeMB: 2048
replSetName: configReplSet
sharding:
clusterRole: configsvr
processManagement:
fork: true
vi /mongodb/conf/db31.conf
systemLog:
destination: file
path: /mongodb/log/db31.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db31
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
port: 27031
replication:
oplogSizeMB: 2048
replSetName: configReplSet
sharding:
clusterRole: configsvr
processManagement:
fork: true
vi /mongodb/conf/db32.conf
systemLog:
destination: file
path: /mongodb/log/db32.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db32
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
port: 27032
replication:
oplogSizeMB: 2048
replSetName: configReplSet
sharding:
clusterRole: configsvr
processManagement:
fork: true
[mongod@web01 ~]$ mongod -f /mongodb/conf/db30.conf
[mongod@web01 ~]$ mongod -f /mongodb/conf/db31.conf
[mongod@web01 ~]$ mongod -f /mongodb/conf/db32.conf
mongo --port=27030
use admin
config = {_id: 'configReplSet', members: [
{_id: 0, host: '10.0.0.8:27030'},
{_id: 1, host: '10.0.0.8:27031'},
{_id: 2, host: '10.0.0.8:27032'}]}
注:mongodb 2.4以後,雖然要求config server爲replica set,可是不支持arbiter
rs.initiate(config)
[mongodb@wu data]$ mongo --port=27030
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27030/test
> use admin
switched to db admin
> config = {_id: 'configReplSet', members: [
... {_id:0,host:'10.0.0.10:27030'},
... {_id:1,host:'10.0.0.10:27031'},
... {_id:2,host:'10.0.0.10:27032'}]}
{
"_id" : "configReplSet",
"members" : [
{
"_id" : 0,
"host" : "10.0.0.10:27030"
},
{
"_id" : 1,
"host" : "10.0.0.10:27031"
},
{
"_id" : 2,
"host" : "10.0.0.10:27032"
}
]
}
> rs.initiate(config)
{ "ok" : 1 }
configReplSet:OTHER> rs.status()
configReplSet:SECONDARY> exit
bye
[mongodb@wu data]$ mongo --port=27030
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27030/test
configReplSet:PRIMARY> rs.config()
configReplSet:PRIMARY> rs.isMaster()
vi /mongodb/conf/db33.conf
systemLog:
destination: file
path: /mongodb/log/db33.log
logAppend: true
net:
port: 27033
sharding:
configDB: configReplSet/10.0.0.8:27030,10.0.0.8:27031,10.0.0.8:27032
processManagement:
fork: true
[mongodb@wu data]$ mongos -f /mongodb/conf/db33.conf
about to fork child process, waiting until server is ready for connections.
forked process: 19196
child process started successfully, parent exiting
[mongodb@wu data]$ ps -ef|grep mongos
mongodb 19196 1 0 13:38 ? 00:00:02 mongos -f /mongodb/conf/db33.conf
mongodb 19275 14772 0 14:05 pts/2 00:00:00 grep mongos
vi /mongodb/conf/db34.conf
systemLog:
destination: file
path: /mongodb/log/db34.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db34
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
port: 27034
replication:
oplogSizeMB: 2048
replSetName: sh1RS
sharding:
clusterRole: shardsvr
processManagement:
fork: true
vi /mongodb/conf/db35.conf
systemLog:
destination: file
path: /mongodb/log/db35.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db35
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
port: 27035
replication:
oplogSizeMB: 2048
replSetName: sh1RS
sharding:
clusterRole: shardsvr
processManagement:
fork: true
vi /mongodb/conf/db36.conf
systemLog:
destination: file
path: /mongodb/log/db36.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db36
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
port: 27036
replication:
oplogSizeMB: 2048
replSetName: sh1RS
sharding:
clusterRole: shardsvr
processManagement:
fork: true
vi /mongodb/conf/db37.conf
systemLog:
destination: file
path: /mongodb/log/db37.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db37
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
port: 27037
replication:
oplogSizeMB: 2048
replSetName: sh2RS
sharding:
clusterRole: shardsvr
processManagement:
fork: true
vi /mongodb/conf/db38.conf
systemLog:
destination: file
path: /mongodb/log/db38.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db38
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
port: 27038
replication:
oplogSizeMB: 2048
replSetName: sh2RS
sharding:
clusterRole: shardsvr
processManagement:
fork: true
vi /mongodb/conf/db39.conf
systemLog:
destination: file
path: /mongodb/log/db39.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/data/db39
directoryPerDB: true
#engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
net:
port: 27039
replication:
oplogSizeMB: 2048
replSetName: sh2RS
sharding:
clusterRole: shardsvr
processManagement:
fork: true
配置完成後啓動6個節點。
[mongod@web01 conf]$ mongod -f db34.conf
[mongod@web01 conf]$ mongod -f db35.conf
[mongod@web01 conf]$ mongod -f db36.conf
[mongod@web01 conf]$ mongod -f db37.conf
[mongod@web01 conf]$ mongod -f db38.conf
[mongod@web01 conf]$ mongod -f db39.conf
配置shard1 RS:
mongo --port=27034
use admin
config = {_id: 'sh1RS', members: [
{_id: 0, host: '10.0.0.8:27034'},
{_id: 1, host: '10.0.0.8:27035'},
{_id: 2, host: '10.0.0.8:27036'}]}
rs.initiate(config)
--------------------
配置shard2 RS:
mongo --port=27037
use admin
config = {_id: 'sh2RS', members: [
{_id: 0, host: '10.0.0.8:27037'},
{_id: 1, host: '10.0.0.8:27038'},
{_id: 2, host: '10.0.0.8:27039'}]}
rs.initiate(config)
---------
鏈接到其中一個mongos進程,作如下配置
# su - mongod
$ mongo --port=27033 admin
> db.runCommand( { addshard : "sh1RS/10.0.0.8:27034,10.0.0.8:27035,10.0.0.8:27036",name:"shard1"} )
> db.runCommand( { addshard : "sh2RS/10.0.0.8:27037,10.0.0.8:27038,10.0.0.8:27039",name:"shard2"} )
mongos> db.runCommand( { listshards : 1 } )
到此爲止分片集羣搭建成功。
[mongodb@wu data]$ mongo --port=27033 admin
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1:27033/admin
mongos> db.runCommand( { addshard : "sh1RS/10.0.0.10:27034,10.0.0.10:27035,10.0.0.10:27036",name:"shard1"})
{ "shardAdded" : "shard1", "ok" : 1 }
mongos> db.runCommand( { addshard : "sh2RS/10.0.0.10:27034,10.0.0.10:27035,10.0.0.10:27039",name:"shard2"})
{
"ok" : 0,
"errmsg" : "in seed list sh2RS/10.0.0.10:27034,10.0.0.10:27035,10.0.0.10:27039, host 10.0.0.10:27034 does not belong to replica set sh2RS; found { hosts: [ \"10.0.0.10:27037\", \"10.0.0.10:27038\", \"10.0.0.10:27039\" ], setName: \"sh2RS\", setVersion: 1, ismaster: true, secondary: false, primary: \"10.0.0.10:27037\", me: \"10.0.0.10:27037\", electionId: ObjectId('7fffffff0000000000000001'), maxBsonObjectSize: 16777216, maxMessageSizeBytes: 48000000, maxWriteBatchSize: 1000, localTime: new Date(1536130591092), maxWireVersion: 4, minWireVersion: 0, ok: 1.0 }",
"code" : 96
}
mongos> db.runCommand( { addshard : "sh2RS/10.0.0.10:27037,10.0.0.10:27038,10.0.0.10:27039",name:"shard2"})
{ "shardAdded" : "shard2", "ok" : 1 }
mongos> db.runCommand({listshards:1})
{
"shards" : [
{
"_id" : "shard1",
"host" : "sh1RS/10.0.0.10:27034,10.0.0.10:27035,10.0.0.10:27036"
},
{
"_id" : "shard2",
"host" : "sh2RS/10.0.0.10:27037,10.0.0.10:27038,10.0.0.10:27039"
}
],
"ok" : 1
}
mongos>
登錄admin數據庫:
mongo -uroot -p123456 192.168.88.53:30000/admin
一、激活數據庫分片功能
admin> ( { enablesharding : "數據庫名稱" } )
eg:
admin> db.runCommand( { enablesharding : "test" } )
二、指定分片建對集合分片
eg:範圍片鍵
--建立索引
admin> db.vast.ensureIndex( { id: 1 } )
admin> db.runCommand( { shardcollection : "test.vast",key : {id: 1} } )
三、集合分片驗證
admin> use test
test> for(i=0;i<2000000;i++){ db.vast.insert({"id":i,"name":"shenzheng","age":70,"date":new Date()}); }
test> db.vast.stats()
三、分片鍵
--範圍片鍵
admin> sh.shardCollection("數據庫名稱.集合名稱",key : {分片鍵: 1} )
或
admin> db.runCommand( { shardcollection : "數據庫名稱.集合名稱",key : {分片鍵: 1} } )
eg:
admin > sh.shardCollection("test.vast",key : {id: 1} )
或
admin> db.runCommand( { shardcollection : "test.vast",key : {id: 1} } )
--哈希片鍵
admin > sh.shardCollection( "數據庫名.集合名", { 片鍵: "hashed" } )
eg:
建立哈希索引
admin> db.vast.ensureIndex( { a: "hashed" } )
admin > sh.shardCollection( "test.vast", { a: "hashed" } )
四、判斷是否Shard集羣
admin> db.runCommand({ isdbgrid : 1})
五、列出全部分片信息
admin> db.runCommand({ listshards : 1})
六、列出開啓分片的數據庫
admin> use config
config> db.databases.find( { "partitioned": true } )
config> db.databases.find() //列出全部數據庫分片狀況
七、查看分片的片鍵
config> db.collections.find()
{
"_id" : "test.vast",
"lastmodEpoch" : ObjectId("58a599f19c898bbfb818b63c"),
"lastmod" : ISODate("1970-02-19T17:02:47.296Z"),
"dropped" : false,
"key" : {
"id" : 1
},
"unique" : false
}
八、查看分片的詳細信息
admin> db.printShardingStatus()
或
admin> sh.status()
主分片
> db.adminCommand({"connPoolStats" : 1})
{
"createdByType": {
"sync": 857,
"set": 4
},
"numDBClientConnection": 35,
"numAScopedConnection": 0,
"hosts": {
"config-01:10005,config-02:10005,config-03:10005": {
"created": 857,
"available": 2
},
"spock/spock-01:10005,spock-02:10005,spock-03:10005": {
"created": 4,
"available": 1
}
},
"totalAvailable": 3,
"totalCreated": 861,
"ok": 1
}
注:
1)形如"host1,host2,host3"的主機名是來自配置服務器的鏈接,也就是用於「同步」的鏈接。
形如"name/host1, host2,...,hostN"的主機是來自分片的鏈接。available的值代表當前實例的鏈接池中有多少可用鏈接。
2)在一個分片上執行connPoolStats,輸出信息中可看到該分片與其餘分片間的鏈接,包括鏈接到其餘分片作數據遷移的鏈接。
分片的主鏈接會直接鏈接到另外一分片的主鏈接上,而後從目標分片吸收數據。
3)進行遷移時,分片會創建一個ReplicaSetMonitor(該進程用於監控副本集的健康情況),
用於追蹤記錄遷移另外一端分片的健康情況。因爲mongod不會銷燬這個監控器,
因此有時會在一個副本集的日誌中看到其餘副本集成員的信息。這是很正常的,不會對應用程序形成任何影響。
對於mgdb的shard集羣來講,添加一個分片很簡單, AddShard就能夠了.
可是縮減集羣(刪除分片)通常不多用到. 因爲某服務器掛了,因此送修前必須把它上面的數據自動遷移到其餘shard上.
一、執行RemoveShard命令
db.runCommand( { removeshard: "your_shard_name" } )
{ msg : "draining started successfully" , state: "started" , shard :"mongodb0" , ok : 1 }
上面這句會當即返回,實際在後臺執行。
二、查看遷移狀態
咱們能夠反覆執行上面語句,查看執行結果。
db.runCommand( { removeshard: "your_shard_name" } )
{ msg: "draining ongoing" , state: "ongoing" , remaining: { chunks: 42, dbs : 1 }, ok: 1 }
從上面能夠看到, 正在遷移,還剩下42塊沒遷移完。
當remain爲0以後, 這一步就結束了。
三、移出非shard數據
db.runComand({movePrimary:」myapp」, to:’’mongodb1’’})
此次就不是當即返回了,要好久,而後會返回以下:
{「primary」:」mongodb1」,」ok」:1}
四、上面步驟完成後,還須要再執行一次RemoveShard,清理殘餘數據
db.runCommand({removeshard:」mongodb0」})
執行成功後,會以下結果.
{msg:’’remove shard completed succesfully,stage: completed",host:"mongodb0",ok:1}
顯示completed後,就能夠安心的關閉mongod的進程了。
官方文檔: http://docs.mongodb.org/manual/tutorial/remove-shards-from-cluster
注意官方關因而否須要運行movePrimary的說明
----------------------------
三個中心
北京核心機房(公司): vm1
北京亦莊災備機房: vm2
上海分部IDC: vm3
--------------------------------
configserver的災備:
vm1:config1+config2+config3====》ConfigRS
vm2:config4 =====》ConfigRS
vm :config5 =====》ConfigRS
------------------------------
shard的災備:shard1
vm1:S1+S2+S3 ---》shard1
vm2:s4 =====》shard1
vm3 :s5 =====》shard1
-------------------
mongos
vm1 mongos1
vm2 mongos2
vm3 mongos3
----------------------
邏輯
mongoexport/mongoimport
mongodump/mongorestore
物理
拷貝文件
卷/磁盤快照
若是mongod實例中日誌功能未開啓,或者是日誌在另外的捲上,得到一致狀態的備份是比較困難的。
刷新內存數據到硬盤,而且中止寫操做:
db.fsyncLock()
Copy / snapshot
db.fsyncUnlock()
Mongodb自帶了mongodump和mongorestore這兩個工具來實現對數據的備份和恢復還原。
mongodump可以在Mongodb運行時進行備份,它的工做原理是對運行的Mongodb作查詢,而後將全部查到的文檔寫入磁盤。可是存在的問題時使用mongodump產生的備份不必定是數據庫的實時快照,若是咱們在備份時對數據庫進行了寫入操做,則備份出來的文件可能不徹底和Mongodb實時數據相等。另外在備份時可能會對其它客戶端性能產生不利的影響。
mongodump用法以下:
$ mongodump --help
參數說明:
-h:指明數據庫宿主機的IP
-u:指明數據庫的用戶名
-p:指明數據庫的密碼
-d:指明數據庫的名字
-c:指明collection的名字
-o:指明到要導出的文件名
-q:指明導出數據的過濾條件
-j, --numParallelCollections= number of collections to dump in parallel (4 by default) 並行轉儲的集合的數量
具體使用示例以下:
$ cd /home/mongod/backup/
--備份test庫
$ mongodump -h 192.168.1.21:30000 -uroot -proot --authenticationDatabase admin -d test -o /home/mongod/backup/
--備份test庫下的vast集合
$ mongodump -h 192.168.1.21:30000 -uroot -proot --authenticationDatabase admin -d test -c vast -o /home/mongod/backup/
--壓縮備份
$ mongodump -h 192.168.1.21:30000 -uroot -proot --authenticationDatabase admin -d test -o /home/mongod/backup/ --gzip
$ mongodump -h 192.168.1.21:30000 -uroot -proot --authenticationDatabase admin -d test -c vast -o /home/mongod/backup/ --gzip
壓縮備份的結果
[root@wu wu]# mongodump -h 127.0.0.1:27017 -o /wu/ --gzip
2018-09-11T12:00:54.107+0800 writing admin.system.users to
2018-09-11T12:00:54.108+0800 done dumping admin.system.users (2 documents)
2018-09-11T12:00:54.134+0800 writing admin.system.version to
2018-09-11T12:00:54.135+0800 done dumping admin.system.version (1 document)
2018-09-11T12:00:54.135+0800 writing mapList.examMapId to
2018-09-11T12:00:54.135+0800 writing app.movies to
2018-09-11T12:00:54.136+0800 writing mapList.resMapId to
2018-09-11T12:00:54.136+0800 writing app.xxxxx to
2018-09-11T12:00:54.137+0800 done dumping mapList.examMapId (11 documents)
2018-09-11T12:00:54.137+0800 writing app.888 to
2018-09-11T12:00:54.137+0800 done dumping app.movies (2 documents)
[root@wu wu]# ll
total 16
drwxr-xr-x 2 root root 4096 Sep 11 12:00 admin
drwxr-xr-x 2 root root 4096 Sep 11 12:00 app
drwxr-xr-x 2 root root 4096 Sep 11 12:00 mapList
-rw-r--r-- 1 root root 108 Aug 30 15:14 test.sh
[root@wu wu]# ll app/
-rw-r--r-- 1 root root 23 Sep 11 12:00 888.bson.gz
-rw-r--r-- 1 root root 94 Sep 11 12:00 888.metadata.json.gz
-rw-r--r-- 1 root root 23 Sep 11 12:00 bbbb.bson.gz
-rw-r--r-- 1 root root 93 Sep 11 12:00 bbbb.metadata.json.gz
-rw-r--r-- 1 root root 23 Sep 11 12:00 cccccc.bson.gz
-rw-r--r-- 1 root root 93 Sep 11 12:00 cccccc.metadata.json.gz
mongorestore是Mongodb從備份中恢復數據的工具,它主要用來獲取mongodump的輸出結果,並將備份的數據插入到運行的Mongodb中。
mongorestore命令使用方法以下:
$ mongorestore --help
參數說明:
-h:指明數據庫宿主機的IP
-u:指明數據庫的用戶名
-p:指明數據庫的密碼
-d:指明數據庫的名字
-c:指明collection的名字
-j, --numParallelCollections= number of collections to restore in parallel (4 by default) 並行恢復的集合數
--恢復test庫
$ mongorestore -h 192.168.1.21:30000 -uroot -proot --authenticationDatabase admin -d test /home/mongod/backup/test/
--恢復test庫下的vast集合
$ mongorestore -h 192.168.1.21:30000 -uroot -proot --authenticationDatabase admin -d test -c vast /home/mongod/backup/test/vast.bson
注:--drop表示恢復的時候把以前的集合drop掉
$ mongorestore -h 192.168.1.21:30000 -uroot -proot --authenticationDatabase admin -d test --drop /home/mongod/backup/test/
$ mongorestore -h 192.168.1.21:30000 -uroot -proot --authenticationDatabase admin -d test -c vast --drop /home/mongod/backup/test/vast.bson
[root@iZuf62o440hd7ir1f41ahdZ mongo-bak]# pwd
/mongo-bak
[root@iZuf62o440hd7ir1f41ahdZ mongo-bak]# ll dump/
total 24
drwxr-xr-x 2 root root 20480 Sep 10 18:02 eduStatistics
drwxr-xr-x 2 root root 4096 Sep 10 18:01 mapList
[root@iZuf62o440hd7ir1f41ahdZ mongo-bak]# mongorestore -h 10.27.120.82:9012 -d eduStatistics --drop dump/eduStatistics/
1. 經常使用命令格式
mongoexport -h IP --port 端口 -u 用戶名 -p 密碼 -d 數據庫 -c 表名 -f 字段 -q 條件導出 --csv -o 文件名
參數重點說明:
-f 導出指定字段,以逗號分割,-f uid,name,age導出uid,name,age這三個字段
-q 能夠根據查詢條件導出,-q '{ "uid" : "100" }' 導出uid爲100的數據
--csv 表示導出的文件格式爲csv的。這個比較有用,由於大部分的關係型數據庫都是支持csv,在這裏有共同點
2. 導出整張表
mongoexport -d SERVERLOG -c users -o /data/mongobak/SERVERLOG.bak/users.dat
connected to: 127.0.0.1
exported 4 records
3. 導出表中部分字段
mongoexport -d SERVERLOG -c users --csv -f uid,name,age -o /data/mongobak/SERVERLOG.bak/users.csv
connected to: 127.0.0.1
exported 4 records
4. 根據條件導出數據
mongoexport -d SERVERLOG -c users -q '{uid:{$gt:1}}' -o /data/mongobak/SERVERLOG.bak/users.json
connected to: 127.0.0.1
exported 3 records
1. 經常使用命令格式
恢復整表導出的非csv文件
mongoimport -h IP --port 端口 -u 用戶名 -p 密碼 -d 數據庫 -c 表名 --upsert --drop 文件名
--upsert:插入或者更新現有數據
恢復部分字段的導出文件
mongoimport -h IP --port 端口 -u 用戶名 -p 密碼 -d 數據庫 -c 表名 --upsertFields 字段 --drop 文件名
--upsertFields:更新部分的查詢字段,必須爲索引,以逗號分隔.
恢復導出的csv文件
mongoimport -h IP --port 端口 -u 用戶名 -p 密碼 -d 數據庫 -c 表名 --type 類型 --headerline --upsert --drop 文件名
--type:導入的文件類型(默認json)
2. 恢復導出的表數據
mongoimport -d SERVERLOG -c users --upsert /data/mongobak/SERVERLOG.bak/users.dat
connected to: 127.0.0.1
Tue Dec 3 08:26:52.852 imported 4 objects
3. 部分字段的表數據導入
mongoimport -d SERVERLOG -c users --upsertFields uid,name,age /data/mongobak/SERVERLOG.bak/users.dat
connected to: 127.0.0.1
Tue Dec 3 08:31:15.179 imported 4 objects
4. 恢復csv文件
mongoimport -d SERVERLOG -c users --type csv --headerline --file /data/mongobak/SERVERLOG.bak/users.csv
connected to: 127.0.0.1
Tue Dec 3 08:37:21.961 imported 4 objects
--file:須要導入的文件
mongodump能夠backup整個數據庫,而mongoexport要對每一個collection進行操做,
最主要的區別也是選擇的標準是mongoexport輸出的JSON比Mongodump的BSON可讀性更高,
進而能夠直接對JSON文件進行操做而後還原數據(BSON轉換JSON存在潛在兼容問題)。
爲何要監控?
監控及時得到應用的運行狀態信息,在問題出現時及時發現。
--被動監控、主動監控
--沒有監控(不能及時掌握線上應用情況、問題不能及時發現)
監控什麼?
機器資源
--CPU、內存、磁盤I/O
應用程序(MongoDB)
--進程監控(ps -aux)
--錯誤日誌監控
。。。
--查看實例運行狀態(內存使用、鎖、用戶鏈接等信息)
--經過比對先後快照進行性能分析
db.serverStatus()重要指標:
"connections"
"activeClients"
"locks"
"opcounters"
"opcountersRepl"
"storageEngine" :查看數據庫的存儲引擎
"mem"
my_repl:SECONDARY> db.serverStatus().connections
{ "current" : 3, "available" : 816, "totalCreated" : NumberLong(6) }
--查看當前數據庫狀態。
my_repl:SECONDARY> use app
switched to db app
my_repl:SECONDARY> db.stats()
{
"db" : "app",
"collections" : 8,
"objects" : 2,
"avgObjSize" : 74,
"dataSize" : 148,
"storageSize" : 45056,
"numExtents" : 0,
"indexes" : 8,
"indexSize" : 45056,
"ok" : 1
}
my_repl:SECONDARY>
--實時數據庫狀態,讀寫、加鎖、索引命中、缺頁中斷、讀寫等待隊列等狀況。
--每秒刷新一次狀態值,並能提供良好的可讀性,經過這些參數能夠觀察到MongoDB系統總體性能狀況。
mongostat重要指標:
insert:每秒插入量
query:每秒查詢量
update:每秒更新量
delete:每秒刪除量
command:一秒內執行的命令數
flushes:一秒內flush的次數通常都是0,或者1,經過計算兩個1之間的間隔時間,能夠大體瞭解多長時間 flush一次。flush開銷是很大的,若是頻繁的flush,可能就要找找緣由了。
conn:當前鏈接數
qr|qw:客戶端查詢排隊長度(讀|寫)
最好爲0,若是有堆積,數據庫處理慢。
ar|aw:活躍客戶端數量(讀|寫)
time:當前時間
mongostat -h 192.168.0.3:9012 -uroot -ppasswd --authenticationDatabase admin
[root@local ~]# mongostat -h 192.168.0.3 --port 9012
connected to: 192.168.0.3:9012
insert query update delete getmore command flushes mapped vsize res faults locked db idx miss % qr|qw ar|aw netIn netOut conn time
*0 *0 *0 *0 0 7|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 404b 6k 32 18:20:44
*0 *0 *0 *0 0 2|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 120b 5k 32 18:20:45
*0 *0 *0 *0 0 1|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 62b 5k 32 18:20:46
*0 *0 *0 *0 0 1|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 62b 5k 32 18:20:47
*0 *0 *0 *0 0 3|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 170b 5k 32 18:20:48
*0 *0 *0 *0 0 1|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 62b 5k 32 18:20:49
*0 *0 *0 *0 0 1|0 0 18.7g 37.8g 2.18g 0 local:0.0% 0 0|0 0|0 62b 5k 32 18:20:50
*0 *0 *0 *0 0 2|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 120b 5k 32 18:20:51
*0 *0 *0 *0 0 4|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 233b 5k 32 18:20:52
*0 *0 *0 *0 0 1|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 62b 5k 32 18:20:53
insert query update delete getmore command flushes mapped vsize res faults locked db idx miss % qr|qw ar|aw netIn netOut conn time
*0 *0 *0 *0 0 7|0 0 18.7g 37.8g 2.18g 0 .:0.0% 0 0|0 0|0 404b 6k 32 18:20:54
--提供結合層的統計信息,默認每秒返回值。
mongotop重要指標:
ns:數據庫命名空間,後者結合了數據庫名稱和集合。
total:mongod在這個命令空間上花費的總時間。
read:在這個命令空間上mongod執行讀操做花費的時間。
write:在這個命名空間上mongod進行寫操做花費的時間。
[root@local ~]# mongotop -h 192.168.0.3:9012
connected to: 192.168.0.3:9012
ns total read write 2018-09-06T10:45:15
eduStatistics.oneExamCnt 0ms 0ms 0ms
eduStatistics.oneExamClassTestRateCnt 0ms 0ms 0ms
eduStatistics.oneExamClassTestRate 0ms 0ms 0ms
eduStatistics.oneExamClassTestOpCnt 0ms 0ms 0ms
eduStatistics.knowledgeUserSubjectRateCnt 0ms 0ms 0ms
eduStatistics.knowledgeUserSubjectRate 0ms 0ms 0ms
eduStatistics.knowledgeUserRateCnt 0ms 0ms 0ms
eduStatistics.knowledgeUserRate 0ms 0ms 0ms
eduStatistics.knowledgeUserCnt 0ms 0ms 0ms
--查看數據庫當前執行什麼操做。
--用於查看長時間運行進程。
--經過(執行時長、操做、鎖、等待鎖時長)等條件過濾。
db.currentOp(
{
"waitingForLock" : true,
$or: [
{ "op" : { "$in" : [ "insert", "update", "remove" ] } },
{ "query.findandmodify": { $exists: true } }
]
}
)
--設置server級別慢日誌。
一、打開profiling: 0不保存, 1保存慢查詢日誌, 2保存全部查詢日誌
注意級別是對應當前的數據庫,而閾值是全局的。
二、查看profiling狀態
三、查看慢查詢:system.profile
四、關閉profiling
硬件。。。(內存、SSD)
收縮數據
增長新的機器、新的副本集
集羣分片鍵選擇
chunk大小設置
預分片(預先分配存儲空間)
優化查詢語句(慢查詢日誌--分析執行計劃)
執行計劃(使用explain)
> db.students.find().explain()
{
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 1,
"nscannedObjects" : 1,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,
"nscannedAllPlans" : 1,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"server" : "SYNC-1:27017",
"filterSet" : false
}
注:
"cursor":BasicCursor表示沒有使用索引,BtreeCursor表示使用了索引。
"n":表示返回的文檔數量。
"nscanned":表示查詢了多少個文檔。
"millis":耗時(毫秒)。
"indexBounds":所用的索引。