美文网首页
04-MongoDB集群运维-读取副本集设置

04-MongoDB集群运维-读取副本集设置

作者: 过桥 | 来源:发表于2019-10-22 16:25 被阅读0次

背景

读写分离还需程序访问时进行对应设置,保证读取操作优先子节点

开启操作日志记录,便于观察操作是否分散

database_repl:PRIMARY> use test
switched to db test
database_repl:PRIMARY> db.getProfilingStatus()
{
    "was" : 0,
    "slowms" : 100,
    "sampleRate" : 1,
    "$clusterTime" : {
        "clusterTime" : Timestamp(1571726954, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    },
    "operationTime" : Timestamp(1571726954, 1)
}
database_repl:PRIMARY> db.setProfilingLevel(2)
{
    "was" : 0,
    "slowms" : 100,
    "sampleRate" : 1,
    "ok" : 1,
    "$clusterTime" : {
        "clusterTime" : Timestamp(1571726974, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    },
    "operationTime" : Timestamp(1571726974, 1)
}
database_repl:PRIMARY> 
ProfilingLevel 级别描述
level   0   关闭
level   1   记录慢命令
level   2   记录全部

读取副本集设置

默认情况下,复制集的所有读请求都发到Primary,Driver可通过设置Read Preference来将读请求路由到其他的节点。

primary: 默认规则,所有读请求发到Primary
primaryPreferred: Primary优先,如果Primary不可达,请求Secondary
secondary: 所有的读请求都发到Secondary
secondaryPreferred:Secondary优先,当所有Secondary不可达时,请求Primary
nearest:读请求发送到最近的可达节点上(通过ping探测得出最近的节点)
Python读操作优先子节点
#! /usr/bin/env python
#coding=utf-8

import time, os 
import datetime
from pymongo import MongoClient
from pymongo import ReadPreference
# pip install pymongo

#MongoDB 数据库链接
conn = MongoClient(['192.168.153.128:27017', '192.168.153.129:27017', '192.168.153.130:27017'])

#读操作优先子节点
db = conn.get_database('test', read_preference=ReadPreference.SECONDARY_PREFERRED)

db.products.insert({"name": "py_insert", "age": 123})

print(db.products.find())
C#读操作优先子节点
using MongoDB.Driver;
using MongoDB.Driver.Linq;

private MongoUnitily()
{
    dataBase = new MongoClient(new MongoClientSettings
    {
        Credentials = new List<MongoCredential>() {
           MongoCredential.CreateCredential("avatar","*******","*********")  // 数据库名称,用户名,用户密码
        },
        Servers = new string[] { "192.168.153.128:27017", "192.168.153.129:27017", "192.168.153.130:27017"}.Select(x=> { return new MongoServerAddress(x); }), // 集群IP地址
        ConnectionMode = ConnectionMode.ReplicaSet, // Replica 模式
        ReplicaSetName = "RS01",   // Replica名称
        
        ReadPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred), // 读操作优先子节点
        
        ConnectTimeout = new TimeSpan(0, 0, 0, 3, 0),  
        MaxConnectionIdleTime = new TimeSpan(0, 0, 0, 3, 0),   
        MaxConnectionLifeTime = new TimeSpan(0, 0, 0, 3, 0),   
        ServerSelectionTimeout = new TimeSpan(0, 0, 0, 3, 0)   
    }).GetDatabase(database);   // 通过数据库名称获取 DbBase
}

相关文章

网友评论

      本文标题:04-MongoDB集群运维-读取副本集设置

      本文链接:https://www.haomeiwen.com/subject/rznqvctx.html