原文地址
python
用pymongo鏈接mongo副本集(Replica Set) 從而讀寫分離以及主備切換進而解決主節點故障問題。
mongodb
獲取副本集實例的 Connection String URI 鏈接信息,詳情請參考Connection String URI
ConnectionString主要內容:數據庫
mongodb://username:password@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/admin?replicaSet=myRepl&authSource=admin
authSource
默認爲鏈接字符串中指定的數據庫。readPreference=secondaryPreferred
,設置讀請求爲Secondary節點優先。更多讀選項請參考Read preferences。mongodb://username:password@dds-xxxxxxxxxxxx:3007,xxxxxxxxxxxx:3007/admin?replicaSet=mgset-xxxxxx&readPreference=secondaryPreferred
經過以上Connection String 來鏈接MongoDB副本集實例,讀請求將優先發給Secondary節點實現讀寫分離。同時客戶端會自動檢測節點的主備關係,當主備關係發生變化時,自動將寫操做切換到新的Primary節點上,以保證服務的高可用。
url
def get_mongo_conn_url_replicaset(ip_port_list, user=None, pwd=None, set_name=None,set_authSource=None): url = 'mongodb://' if user is not None: if pwd is None: pwd = user url += '%s:%s@' % (user, pwd) url += ','.join(ip_port_list) if set_name is not None: url += '/?replicaSet=%s&authSource=%s&readPreference=secondaryPreferred' % (set_name,set_authSource) return url ip_port_list = ['m3007.test.mongodb.m.com:3777', 's3007.test1.mongodb.m.com:3777', 's3007.test2.mongodb.m.com:3777'] conn_url = get_mongo_conn_url_replicaset(ip_port_list, "username", "password", "rs_3777","admin") cli = MongoClient(conn_url)