Leonid Beschastny
Leonid Beschastny

Reputation: 51470

Read-only connection to a slave instance using monger

I have a replica set and I want to establish standalone read-only connection to a slave instance.

Normally, I should experience no problems doing it. The only thing I ought to do is to set slaveOk=true to be able to query it with read operations. It works great when I'm using nodejs or mongo console, but I found no way to do it using monger.

The strangest thing is that I'm getting an exception when I'm calling set-db! function:

MongoException not talking to master and retries used up com.mongodb.DBTCPConnector.innerCall (DBTCPConnector.java:314)

Establishing replica-set connection is not an option for me.

Currently I'm using [com.novemberain/monger "1.4.0"].

Thanks!


Update: I looked through Java MongoDB Driver API Documentation and found slaveOk method. I wrote the following code, hoping it'll work:

(defn slave-connect!
  [& args]
  (mg/set-connection!
    (doto (apply mg/connect args)
          (.slaveOk))))

But all I've got is a new exception:

MongoException not master com.mongodb.CommandResult.getException (CommandResult.java:100)

Upvotes: 2

Views: 8325

Answers (2)

Leonid Beschastny
Leonid Beschastny

Reputation: 51470

Looks like I solved my problem using com.mongodb.DBApiLayer Documentation.

So, the right solution is to set ReadPreference to secondary using setReadPreference method and then to make the database read-only using setReadOnly() method:

(import 'com.mongodb.ReadPreference)

(defn use-slave-db!
  [& args]
  (mg/set-db!
    (doto (apply mg/get-db args)
          (.setReadOnly true)
          (.setReadPreference
            (ReadPreference/secondary)))))

Now whe are able to connect to a slave instance using use-slave-db! function instead of default use-db! macro.

Upvotes: 1

Matt
Matt

Reputation: 550

I found the following works too under monger 2.0.0:

(connect-via-uri "mongodb://host/db?readOnly=true&readPreference=secondary")

Upvotes: 2

Related Questions