Background

根據上一篇 Implement MongoDB Replication Sets on Ubuntu (1) 我們了解到怎麼建立 MongoDB Replication.
那這篇我希望能夠好好測試我們所建好的Replication環境.

Insert Data

先自己隨便從 Primary Insert 幾筆資料進去, 但記得 Insert 前要先去admin那邊驗證.

use admin
db.auth("siteRootAdmin", "<password>");

如果Insert成功後要去另外兩台(Secondary), 看一下資料有沒有同步成功. 但是應該會遇到下面的問題.

MongoDB的“not master and slaveok=false” error

Mongodb default 是 slaveok=false 所以你在Secondary是不能下Query指令的. 要解決的話就必須run下面的指令.

# running in a mongo shell 
rs.slaveOk()

MongoDB Write Concern

  • Errors Ignored [-1]
  • 發出write operation後就不再理會
  • Unacknowledged [0]
  • 這個驅動會根據當前系統的網絡配置進行網絡問題的檢測,不等待Mongd的返回
  • Acknowledged [1][default]
  • 這個級別算是中等級別的配置,這個級別能夠拿到mongod的返回信息
  • Journaled [1, journal=true ]
  • 這種情況可以容忍服務器突然斷線,斷電等意外的恢復
  • Replica Acknowledged [>1 or majority]
  • 確保有同步到Secondary

Modify Default Write Concern

說明連結

cfg = rs.conf()
cfg.settings = {}
cfg.settings.getLastErrorDefaults = { w: "majority", wtimeout: 5000 }
rs.reconfig(cfg)

Read Preference Mode

以下是官方所提出的幾種 Read Preference Mode

  • Primary
  • Default mode. All operations read from the current replica set primary.
  • PrimaryPreferred
  • In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.
  • Secondary
  • All operations read from the secondary members of the replica set.
  • SecondaryPreferred
  • In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.
  • Nearest
  • Operations read from member of the replica set with the least network latency, irrespective of the member’s type.

Read via Pymongo

以下是利用 python 透過 pymongo 來連線到 MongoDB 的 Replication sets, 並讀取資料. 但我的環境都是建立在 GCP 的平台, 所以都是走內網. 如果你要走外網的話我有嘗試過但是遇到一個奇怪的問題 [Errno 8] nodename nor servname provided, 我猜是跟Network相關, 因為我在三台機器上的Host的ip資訊都是填內網ip(/ect/host), 可能因此有問題. (但是我未來的需求都是建立在內網連線, 所以我就不繼續研究了)

# -*- coding: utf-8 -*-  
from pymongo import MongoClient
client = MongoClient('mongodb://USER:' + PASSWORD + '@IP1,IP2,IP3', replicaSet='rs0', readPreference='secondaryPrefe
rred')

print(client)
db = client[DB_NAME]
col = db[COLLECTION_NAME]
res = col.find_one()
print(res)

Write via Pymongo

在Replication的環境中, 只能寫入到Primary那台server. 但是在程式Connection的部分不用特別去做調整, 看起來會自動去抓Primary機器的位址然後寫入.

# -*- coding: utf-8 -*-  
from pymongo import MongoClient
client = MongoClient('mongodb://USER:' + PASSWORD + '@IP1,IP2,IP3', replicaSet='rs0', readPreference='secondaryPreferred')

print(client)
db = client['test']
col = db['write']
data = {
    "name": "Paul",
    "phone": "0933222111",
}
res = col.insert(data)

Reference