Golang MGO driver specifies MONGO server read

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Replica Sets Construction

The server is built with Replica sets and can be referenced by deploy a Replica Set

Read mode

There are five types of reading modes in Mongod:

    • Primary. Perform all read operations on the master node
    • Primarypreferred. Read operations are preferred on the primary node, if the primary node is unavailable and then from the node.
    • Secondary. All read operations are performed on the slave node.
    • Secondarypreferred. Priority is read from the node, if all slave nodes are not available, then operate from the master node.
    • Nearest. Depending on the network latency, read operations are performed nearby, regardless of the node type.

Configuration Node Tags sets

Tag sets allows you to specify a replica set for read operations where the read mode of Mongod must be one of the following four types:
primaryPreferred, secondary , secondaryPreferred ,nearest
Tags Sets Configuration reference: Configure Replica Set Tag Sets
The main operations are as follows:

conf = rs.conf()conf.members[0].tags = { "dc": "east", "use": "production"  }conf.members[1].tags = { "dc": "east", "use": "reporting"  }conf.members[2].tags = { "use": "production"  }rs.reconfig(conf)

MgO code Example

Depending on the configuration above, if you need to specify a database read from members 1, you can take the following code:

session, err := mgo.Dial("localhost")if err != nil {    log.Fatalln(err)}defer session.Close()session.SetMode(mgo.Eventual, true) //需要指定为Eventualsession.SelectServers(bson.D{{"dc", "east"}, {"use", "reporting"}}) // 指定从1中读取db := session.DB("test")col := db.C("tbl")data := make([]interface{}, 10)col.Find(nil).Limit(10).All(&data)log.Println(data)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.