How to set MongoDB ReadPreference in Spring MVC's contextConfigLocation How to set MongoDB ReadPreference in Spring MVC's contextConfigLocation mongodb mongodb

How to set MongoDB ReadPreference in Spring MVC's contextConfigLocation


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>


Expanding @Trisha's response in to an answer: "Do it in MongoTemplate programmatically" by setting the ReadPreference to SECONDARY.

MongoTemplate template = new MongoTemplate(...);template.setReadPreference(com.mongodb.ReadPreference.SECONDARY);


In case you are using spring-data-mongodb and have some requirement to use multiple Read Preferences based on find query, you can create multiple Mongo Templates and/or Repositories like

    @EnableMongoRepositories(basePackages = {            "com.you.repo.package" }, mongoTemplateRef = "mongoTemplateOne")        @Configuration    public class MongoConfig {    @Bean(name="mongoTemplateOne")    public MongoTemplate getMongoTemplateOne() throws UnknownHostException {        MongoTemplate templateOne = new MongoTemplate(new SimpleMongoDbFactory(new MongoClientURI("YOUR_MONGO_URL")));        templateOne.setReadPreference(ReadPreference.secondaryPreferred());        //setting WriteConcern but not relevant for this thread        templateOne.setWriteConcernResolver(yourWriteConcernResolver());        return templateOne;    }    @Bean(name = "mongoTemplateTwo")    public MongoTemplate getMongoTemplateTwo() throws UnknownHostException {        MongoTemplate templateTwo = new MongoTemplate(new SimpleMongoDbFactory(new MongoClientURI("YOUR_MONGO_URL")));        templateTwo.setReadPreference(ReadPreference.secondaryPreferred());        return templateTwo;    }    private WriteConcernResolver yourWriteConcernResolver() {        return action -> {            if (action.getCollectionName()                    .equals("your_collecton")                    && (action.getMongoActionOperation() == MongoActionOperation.SAVE                            || action.getMongoActionOperation() == MongoActionOperation.UPDATE)) {                return WriteConcern.MAJORITY;            }            return action.getDefaultWriteConcern();        };    }