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:
1 2 3 4 5 |
<dependency> <groupId>io.r2dbc</groupId> <artifactId>r2dbc-pool</artifactId> <version>1.0.0.RELEASE</version> </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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Bean public ConnectionFactory connectionFactory() { ConnectionFactoryOptions options = ConnectionFactoryOptions.builder() .option(ConnectionFactoryOptions.DRIVER, "pool") .option(ConnectionFactoryOptions.PROTOCOL, "postgresql") .option(ConnectionFactoryOptions.HOST, "localhost") .option(ConnectionFactoryOptions.USER, "khanh") .option(ConnectionFactoryOptions.PASSWORD, "123456") .option(ConnectionFactoryOptions.DATABASE, "spring_data_r2dbc_example") .option(PoolingConnectionFactoryProvider.MAX_SIZE, 10) .option(PoolingConnectionFactoryProvider.INITIAL_SIZE, 3) .build(); return ConnectionFactories.get(options); } |
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: