Connection pooling in Spring Boot and mongo db
Asked Answered
B

2

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?

Breton answered 5/6, 2018 at 10:48 Comment(0)
E
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);
}
Edp answered 5/6, 2018 at 11:1 Comment(2)
Cant find MongoClientOptions in latest version is there any alternative ?Transferase
With a quick look, I can see that MongoClientSettings is what you should use.Edp
F
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();
            });
}
Fraudulent answered 15/9, 2021 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.