From 75fd7f5c91f63f546f24fe935317fc0314b1a84f Mon Sep 17 00:00:00 2001 From: Baishampayan Ghose Date: Tue, 15 May 2012 11:14:14 +0530 Subject: [PATCH] Add support for connecting to Replica Sets. Monger can now connect to replica sets using one or more seeds when calling monger.core/connect with a vector (or list) of server-addresses instead of just a single one. For example - ;; Connect to a single MongoDB instance (connect (server-address "127.0.0.1" 27017) (mongo-options)) ;; Connect to a replica set (connect [(server-address "127.0.0.1" 27017) (server-address "127.0.0.1" 27018)] (mongo-options)) Since connect! just applies connect to all the args, it works fine there as well. --- src/monger/core.clj | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/monger/core.clj b/src/monger/core.clj index 1deb7d7..2ec8805 100644 --- a/src/monger/core.clj +++ b/src/monger/core.clj @@ -16,7 +16,7 @@ (:use [monger.conversion]) (:import [com.mongodb Mongo MongoURI DB WriteConcern DBObject DBCursor CommandResult Bytes MongoOptions ServerAddress MapReduceOutput] [com.mongodb.gridfs GridFS] - [java.util Map])) + [java.util Map ArrayList])) ;; ;; Defaults @@ -47,11 +47,26 @@ (monger.core/connect) (monger.core/connect { :host \"db3.intranet.local\", :port 27787 }) + + ;; Connecting to a replica set with a couple of seeds + (let [^MongoOptions opts (mg/mongo-options :threads-allowed-to-block-for-connection-multiplier 300) + seeds [[\"192.168.1.1\" 27017] [\"192.168.1.2\" 27017] [\"192.168.1.1\" 27018]] + sas (map #(apply mg/server-address %) seeds)] + (mg/connect! sas opts)) " + {:arglists '([] + [server-address options] + [[server-address & more] options] + [{ :keys [host port uri] :or { host *mongodb-host* port *mongodb-port* }}])} ([] (Mongo.)) - ([^ServerAddress server-address ^MongoOptions options] - (Mongo. server-address options)) + ([server-address ^MongoOptions options] + (if (coll? server-address) + ;; connect to a replica set + (let [server-list ^ArrayList (ArrayList. ^java.util.Collection server-address)] + (Mongo. server-list options)) + ;; connect to a single instance + (Mongo. ^ServerAddress server-address options))) ([{ :keys [host port uri] :or { host *mongodb-host* port *mongodb-port* }}] (Mongo. ^String host ^Long port)))