DEV Community

Shubham Bhati
Shubham Bhati

Posted on

Spring Boot Database Connection Pooling

When working with Spring Boot and PostgreSQL, we've found that connection pooling can make a huge difference in performance. We can't afford to create a new connection for every request, so we use a connection pool to reuse existing connections. Spring Boot makes this easy with the HikariCP library. We just need to add the dependency to our pom.xml file and configure the connection pool properties. For example, we can set the minimum and maximum pool size like this:
@bean
public DataSource dataSource() {
return DataSourceBuilder.create()
.driverClassName("org.postgresql.Driver")
.url("jdbc:postgresql://localhost:5432/mydb")
.username("myuser")
.password("mypassword")
.build();
}
Then we can configure the pool size in our application.properties file: spring.datasource.hikari.minimumPoolSize=5 and spring.datasource.hikari.maximumPoolSize=15. This way, our application doesn't run out of connections when handling a large number of requests.

Top comments (0)