Search code examples
javaspringmongodbspring-bootreplication

Spring boot connect to MongoDB replica set running with an Arbiter


My application is a Spring boot application and the application configuration properties file look like:

....
spring.data.mongodb.host=ip
spring.data.mongodb.port=27017
spring.data.mongodb.admin.database=admin
spring.data.mongodb.database=myDB
spring.data.mongodb.username=su
spring.data.mongodb.password=su1$
....

Now the thing is for high availability MongoDB has been moved to a Primary-Secondary-Arbiter setup. What changes should I do in order to connect to this. Tried separating with comma but that did not help.


Solution

  • As Spring Boot documentation states:

    spring.data.mongodb.host and spring.data.mongodb.port are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri should be used to provide all of the configuration.

    You can set spring.data.mongodb.uri property to change the URL and configure additional settings such as the replica set.

    Suppose you have replica set named mc with mongo1:27017 as Primary, mongo2:27017 as Secondary and mongo3:27017 as the Arbiter, then you can use:

    spring.data.mongodb.uri=mongodb://su:su1$@mongo1:27017,mongo2:27017/myDB?replicaSet=mc
    

    Please note that:

    When connecting to a replica set it is important to give a seed list of at least two mongod instances. If you only provide the connection point of a single mongod instance, and omit the replicaSet, the client will create a standalone connection.

    Using MongoDB connection string you can set other properties such as Read Preference. Take a look at MongoDB documentation for more details.