You can use the MongoClientOptions object to set various optional connection parameters. You are looking at setting your heart rate to make sure you try connecting to your computer again. Also set the socket timeout so that it does not last too long.
- MinHeartbeatFrequency: in case the driver needs to frequently check the availability of the server, it will wait at least as long as the previous check to avoid wasted effort. The default value is 10 ms.
- HeartbeatSocketTimeout: timeout for checking heartbeat
- SocketTimeout: connection timeout
Help API
To avoid excessive code duplication, you can optionally follow the pattern example as shown below. The basic idea is to avoid the configuration associated with connecting to a database that is littered everywhere in projects.
@Component public class MongoConnection{ MongoClient mongoClient = null; ... @PostConstruct public void init() throws Exception {
Now you can use MongoConnection in DAO-s
@Repository public class ExampleDao{ @Autowired MongoConnection mongoConnection; public void insert(BasicDBObject document) { mongoConnection.getCollection("example").insert(document); } }
You can also implement all database operations inside MongoConnection to introduce some common functions in all directions. For example, add logging for all "inserts"
source share