4

I am going through spring boot application and mongoDb connection POC. I have added following dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Also I have gone through mongoB properties with properties: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Can you please how do we define connection pooling mechanism here?

Jagrut Dalwadi
  • 295
  • 1
  • 4
  • 17

2 Answers2

1

You cannot do this out of the box with application properties. You need to make use of MongoClientOptions to configure various aspects of connection pool.

Have a look at the documentation for various options available.

Here is a simple example.

@Bean(name="mongoTempl")
public MongoTemplate mongoTempl() throws Exception {
     return new MongoTemplate(createMongoClient(new ServerAddress(host, port))
                              ,dbName);
}


Mongo createMongoClient(ServerAddress serverAddress) {
final MongoClientOptions options = MongoClientOptions.builder()
        .threadsAllowedToBlockForConnectionMultiplier(...)
        .connectionsPerHost(...)
        .connectTimeout(...)
        .maxWaitTime(...)
        .socketKeepAlive(...)
        .socketTimeout(...)
        .heartbeatConnectTimeout(...)
        .minHeartbeatFrequency(...)
        .build();

        return new MongoClient(serverAddress, options);
}
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
1

You can use also MongoClientSettingsBuilderCustomizer like in this spring sample

@Bean
public MongoClientSettingsBuilderCustomizer customizer() {
    return (builder) -> builder.applyToConnectionPoolSettings(
            (connectionPool) -> {
                connectionPool.maxSize(10);
                connectionPool.minSize(2);
                connectionPool.maxConnectionIdleTime(5, TimeUnit.MINUTES);
                connectionPool.maxWaitTime(2, TimeUnit.MINUTES);
                connectionPool.maxConnectionLifeTime(30, TimeUnit.MINUTES);
                connectionPool.addConnectionPoolListener();
            });
}
Isko
  • 121
  • 1
  • 7