Spring Boot - How to check number of active connections in the connection pool

3.6k Views Asked by At

I am using Spring Boot 1.5.17 with multiple data sources configured. One of my data sources is configured as follows.

@Primary
@Bean
@ConfigurationProperties("app.primary.datasource")
public DataSource primaryDataSource() {

    return DataSourceBuilder.create().build();
}

Now how do I get or log the number of active connections in the connection pool for this data source?

2

There are 2 best solutions below

0
Julin Alex On

It's a bit late , but DataSource interface doesn't have any methods that lets you do this, but if you are using HikariCP (which is the default).

You could do this.

(HikariDataSource)dataSource).getHikariPoolMXBean().getActiveConnections()
0
justCurious On

Solution (Kotlin code):

    @Autowired  var dataSource: DataSource
    val hikaridataSource = dataSource as HikariDataSource
    logger.info(
         active: ${hikaridataSource.hikariPoolMXBean.activeConnections} " + "idle: ${hikaridataSource.hikariPoolMXBean.idleConnections} " + "threadsAwaitingConnection: ${hikaridataSource.hikariPoolMXBean.threadsAwaitingConnection}"
    )