Database Reference
In-Depth Information
But when connecting directly to a replica set secondary, you must indicate that you
know you're connecting to such a node (for most drivers, at least). In the Ruby driver,
you accomplish this with the :slave_ok parameter. Thus to connect directly to the
first secondary you created earlier in the chapter, the Ruby code would look like this:
@con = Mongo::Connection.new('arete', 40001, :slave_ok => true)
Without the :slave_ok argument, the driver will raise an exception indicating that it
couldn't connect to a primary node. This check is in place to keep you from inadver-
tently writing to a secondary node. Though such attempts to write will always be
rejected by the server, you won't see any exceptions unless you're running the opera-
tions with safe mode enabled.
The assumption is that you'll usually want to connect to a primary node master;
the :slave_ok parameter is enforced as a sanity check.
R EPLICA SET CONNECTIONS
You can connect to any replica set member individually, but you'll normally want to con-
nect to the replica set as a whole. This allows the driver to figure out which node is pri-
mary and, in the case of failover, reconnect to whichever node becomes the new
primary.
Most of the officially supported drivers provide ways of connecting to a replica set.
In Ruby, you connect by creating a new instance of ReplSetConnection , passing in a
list of seed nodes:
Mongo::ReplSetConnection.new(['arete', 40000], ['arete', 40001])
Internally, the driver will attempt to connect to each seed node and then call the
isMaster command. Issuing this command to a replica set returns a number of
important set details:
> db.isMaster()
{
"setName" : "myapp",
"ismaster" : true,
"secondary" : false,
"hosts" : [
"arete:40000",
"arete:40001"
],
"arbiters" : [
"arete:40002"
],
"maxBsonObjectSize" : 16777216,
"ok" : 1
}
Once a seed node responds with this information, the driver has everything it needs.
Now it can connect to the primary member, again verify that this member is still pri-
mary, and then allow the user to read and write through this node. The response
object also allows the driver to cache the addresses of the remaining secondary and
Search WWH ::




Custom Search