Session of Golang:mgo Anatomy

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

Golang operation MONGO Use the package is "GOPKG.IN/MGO.V2", coding process need to read and write MONGO database, simply observe the next source, record some of their own understanding, if there are errors, please treatise.

in general, we create a session directly like this :

Session, err = MgO. Dial (URL)

If err! = Nil {

Log. PRINTLN (ERR)

}

Look at Dial What this function does:

Func Dial (URL string) (*session, error) {

Session, Err: = Dialwithtimeout (URL, 10*time. Second)

If Err = = Nil {

Session. Setsynctimeout (1 * time. Minute)

Session. SetSocketTimeout (1 * time. Minute)

}

return session, Err

}

called the Dialwithtimeout function sets the default time-out to ten seconds. The function calls the Dialwithinfo function, while the Dialwithinfo function compares the call to NewSession to see what the function does:

Func newsession (consistency Mode, cluster *mongocluster, timeout time. Duration) (Session *session) {

Cluster. Acquire ()

Session = &session{

Cluster_: Cluster,

Synctimeout:timeout,

Socktimeout:timeout,

poollimit:4096,

}

DEBUGF ("New session%p on Cluster%p", Session, cluster)

Session. SetMode (consistency, true)

Session. Setsafe (&safe{})

Session.queryConfig.prefetch = Defaultprefetch

return session

}

the returned session sets some default parameters, temporarily ignoring them, and looking directly at The data structure of the session:

Type Session struct {

M sync. Rwmutex

Cluster_ *mongocluster

Slavesocket *mongosocket

Mastersocket *mongosocket

slaveok BOOL

Consistency Mode

Queryconfig Query

Safeop *QUERYOP

Synctimeout time. Duration

Socktimeout time. Duration

Defaultdb string

Sourcedb string

Dialcred *credential

creds []credential

Poollimit int

bypassvalidation BOOL

}

Mis aMgO. Sessionthe concurrency lock, so all theSessioninstances are thread-safe. Slavesocket,mastersocketrepresents theSessionto theMongoDBThe primary node and the cache of a physical connection from the node. andSessionpolicies always prioritize the use of cached connections. Whether the connection is cached by theConsistencythat is theSessionthe mode of the decision. Assume that in a concurrent program, you use the sameSessioninstance, do not useCopy, while theSessioninstance, and the pattern of the instances is exactly how the connection is cached, then all theSessionthe operation of the instance will be reached through the same connectionMongoDB. AlthoughMongoDBthe network model itself is non-blocking communication, and requests can be handled in a single link, non-blocking,but it affects efficiency.

Next MgO. the Session caches a primary one from the connection, and the instance itself is not responsible for maintenance. That is, when slavesocket,mastersocket Any one, the connection is disconnected,thesession itself does not reset the cache, the session If the user does not actively reset the cache, the caller will always get EOF. This happens when the master-slave switch occurs, as well as when the network jitter occurs.

  MgO The DB handle requires you to make a Copy Operation:

Copy works just like New, but preserves the exact authentication

Information from the original session.

Func (S *session) Copy () *session {

S.m.lock ()

Scopy: = Copysession (S, true)

S.m.unlock ()

Scopy. Refresh ()

Return scopy

}

Copysessionthe sourceSessionshallow copy to temporarySession, so the sourceSessionthe configuration is copied to a temporarySessionthe. Key toRefresh, the sourceSessionshallow copy to temporarySessionthe connection cache pointer, which isSlavesocket,mastersocketset to empty, so that temporarySessionThere is no cache connection, and it goes to try to get an idle connection.

MgO itself maintains a set of connection pools to the MongoDB cluster. This set of connection pooling mechanism to the mongodb database server is the smallest unit, each MongoDB will be inside the MgO , corresponding to a Mongoserver an instance of a struct that represents the MgO The connection to the database that is held. Look at the definition of this connection pool:

Type Mongoserver struct {

Sync. Rwmutex

ADDR string

RESOLVEDADDR string

Tcpaddr *net. Tcpaddr

Unusedsockets []*mongosocket

Livesockets []*mongosocket

closed bool

abended BOOL

Sync Chan bool

Dial Dialer

Pingvalue time. Duration

Pingindex int

Pingcount UInt32

Pingwindow [6]time. Duration

Info *mongoserverinfo

}

Inforepresents the information in the cluster of the database server that the instance corresponds to--whetherMaster,Replicasetnameand so on. and two ofSlice, is the legendary connection pool. unusedsocketsstores the currently idle connection,livesocketsstores the connection in the current active,SessionThe cached connection is stored at the same timelivesocketsSlice, while the temporarySessionthe acquired connection is located on theunusedsocketsthe slice.

each mongoserver will be subordinate to a mongocluster structure, which is equivalent to MgO in the interior, simulating a MONGO The model of the DB cluster.

Type Mongocluster struct {

Sync. Rwmutex

serversynced sync. Cond

Userseeds []string

Dynaseeds []string

Servers Mongoservers

Masters Mongoservers

References int

syncing bool

direct BOOL

failFast BOOL

Synccount UINT

SetName string

Cachedindex Map[string]bool

Sync Chan bool

Dial Dialer

}

Mongocluster holds An example of a series of Mongoserver that are dispersed into two arrays in a master-slave structure. Each Session will store its own reference to the Mongocluster that is to be manipulated .

The preceding description can be summed up in the following diagram:

Then we can create a session clone operation, with clone get the copysession Complete the operation and close the when finished. copysession it's OK.

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.