Connection pool with R2DBC

The connection pool is how we control the maximum number of connections open to a certain server or database. This is how we save and use resources rationally, avoiding waste. No server can handle an unlimited number of connections!

When working with a reactive database using R2DBC, you also need to ensure this by implementing a connection pool to the database using the R2DBC Pool library.

As follows:

First, if your Java project is a Java Maven project, declare the following dependency:

Next, in the configuration section to initialize the ConnectionFactory as I did in the tutorial Overview of Spring Data R2DBC, please declare the following configurations:

Please notice that the “DRIVER” option has been assigned a different value of “pool”, and the “PROTOCOL” option is assigned the “postgresql” value corresponding to the “pool” driver. If you use other databases than PostgreSQL database, just change the value of the PROTOCOL option, guys!

There are many other options that you can register with the “pool” driver. Here, I only configure 2 necessary options of a connection pool, which is the maximum number of connections that the application can open to the database and the number of connections at initialization. You can also configure the option PoolingConnectionFactoryProvider.MIN_IDLE to specify the number of idle connections when the application has no operations to the database, there are still open connections to the database.

Now, if I run the example in the tutorial Overview of Spring Data R2DBC, I will always see 3 connections open in pgAdmin as follows:

Add Comment