Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set MongoDB ReadPreference in Spring MVC's contextConfigLocation

I am connecting to a MongoDB sharding server via mongodb java driver in Spring MVC. I am using the following versions:

  • spring-webmvc-3.2.1.RELEASE
  • mongo-java-driver/2.10.0/mongo-java-driver-2.10.0
  • spring-data-mongodb-1.2.0.RELEASE

My Mongo options are set in the contextConfigLocation file mvc-dispatcher-servlet.xml

<mongo:mongo host="mongo.sample.com" port="30000">
     <mongo:options auto-connect-retry="true"
                    slave-ok="true"/>
</mongo:mongo>

It works pretty well, but the slave-ok is deprecated by come.MongoDB.ReadPreference. I just wonder if there is any way to set the readPreference for Spring MVC in the contextConfiLocation file.

like image 599
sorebrek Avatar asked Oct 24 '13 02:10

sorebrek


People also ask

Can I use Spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases. You make compromises by using the JPA API for other types of datastores, but it makes it easy to investigate them.


1 Answers

Declare the following bean

<bean id="readPreferenceSecondary" class="com.mongodb.TaggableReadPreference.SecondaryReadPreference">
</bean>

and

you inject this in your mongotemplate

<bean id="mongoTemplateProdDb" class="org.springframework.data.mongodb.core.MongoTemplate" >
        <property name="readPreference" ref="readPreferenceSecondary"></property>
</bean>
like image 69
jaipster Avatar answered Sep 22 '22 17:09

jaipster