Search code examples
javaspringspring-bootconnection-poolingspring-jdbc

Set maxConnectionLimit to Manually created connection using Spring DataSourceBuilder.create()


Using application.properties we can provide the

spring.datasource.hikari.maximum-pool-size=10

as spring using the Hikari connection pooling by default. But when we are creating datasource manually as a specific requirement we cannot use the application.properties.

Scenario.

  1. User will configure the datasource dynamically and that connection object should be available from thereafter.
  2. For this we are creating DatasourceBuilder.create().build() method to create a datasource connection object and set it into the bean factory.
  3. But while creating a datasource connection object using DataSourceBuilder.create().build() method it is creating connection pooling and 10 connection to the database at the same time.
  4. We wanted to avoid that connection pooing and have only one connection.

How do I do that?


Solution

  • While creating the custom datasource we can create an instance of HikariDataSource instead of DataSource.

    Assuming you are using Spring default Connection pooling (Hikari)

    public DataSource createCustomConnection(String driverClass, String url, String username, String password) { 
        HikariConfig config = new HikariConfig();
            config.setDriverClassName(driverClass);
            config.setJdbcUrl(url);
            config.setUsername(username);
            config.setPassword(password);
            config.setMaximumPoolSize(MENTIONED_TOTAL_CONNECTIONS);
            // Like this you can configure multiple properties here 
            
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }
    DataSource dataSource = createCustomConnection(...) // Pass Parameters here
    

    Here you have created the datasource that creates a single connection at the same time.

    for more information https://github.com/brettwooldridge/HikariCP#initialization

    Thank you.