How to enable connection pooling with spring-boot-starter-data-r2dbc?

8.2k Views Asked by At

I have a Spring Boot application with data-r2dbc dependency. I use PostgreSQL as DB.
So I already have in place the following dependencies (gradle notation):

  • org.springframework.boot:spring-boot-starter-data-r2dbc:2.3.5.RELEASE
  • io.r2dbc:r2dbc-postgresql

I need to enable connection pooling for R2DBC connections. Unfortunately, I could not find any exhaustive manual to do so.

According to this quite outdated release notes I have to add also io.r2dbc:r2dbc-pool and use spring.r2dbc.pool.* properties to configure pooling.

Also, according to this reference I do not need to turn on pooling manually because SB will enable it if r2dbc-pool is found on the classpath.

Is it enough or do I miss something?

2

There are 2 best solutions below

0
On BEST ANSWER

Answering my own question.

TLDR

  • Having org.springframework.boot:spring-boot-starter-data-r2dbc:2.3.5.RELEASE is enough to have connection pooling enabled by default
  • No need to add io.r2dbc:r2dbc-postgresql explicitly
  • No need to put :pool: in the URL in this case

Some detailed findings. it seems there are two ways to enable connection pool:

  1. Put :pool: driver chunk into the URL and then io.r2dbc.pool.PoolingConnectionFactoryProvider#create will take care of creating a Connection Pool. This is described at https://github.com/r2dbc/r2dbc-pool#getting-started
  2. Do not have spring.r2dbc.pool.enabled=false in configs (meaning that its absence is interpreted as true by default). This way a Connection Pool will be created by the org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryConfigurations.Pool#connectionFactory. I am not sure, but it looks like a generalized Spring Boot configuration-style override over a library specific :pool: option.

This options are independent and partly overlap and the second one takes precedence.

The second component evaluates also presence of the :pool: in the URL (see org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryConfigurations.PooledConnectionFactoryCondition) and if found it delegates the creation of the Connection Pool to the first one.

There is also a peculiar conclusion - having explicit spring.r2dbc.pool.enabled=false leads to creation of a Connection Pool anyway if there is a :pool: in the URL. Therefore the only way to disable pooling is to have spring.r2dbc.pool.enabled=false and to omit :pool: in the URL at the same time.

0
On

Below code worked for me

String url = "r2dbc:postgres://user:password@hostname:5432/testdb?ApplicationName=myapp";
ConnectionFactory ret= ConnectionFactories.get(url);

ConnectionPoolConfiguration poolConfiguration = ConnectionPoolConfiguration.builder(ret)
                .initialSize(5)                        .maxSize(10).maxIdleTime(Duration.ofMinutes(5)).build();

ConnectionPool pool = new ConnectionPool(poolConfiguration);

return pool;