How to get the number of active DB connections made from spring boot application

I have build a spring boot application with Oracle datasource. I need to print the total active connections in log statement. How to get the active connections. Note - Not max active connections it should be active connection @particular time/instance.

Upvotes: 4

Views: 15438

Answers (2)

DataSource dataSource = (DataSource) jdbcTemplate.getDataSource();
LOGGER.info("Max Idle: " + dataSource.getMaxIdle());
LOGGER.info("Max Active: " + dataSource.getMaxIdle());
LOGGER.info("Active: " + dataSource.getNumActive());
LOGGER.info("Idle: " + dataSource.getNumIdle());

Refered From this link - https://numberformat.wordpress.com/2017/10/20/configuring-a-connection-pool-in-spring-using-dbcp2/

Edit

Answer 2:

For HikariCP you have to enable the debug level logs for the package com.zaxxer.hikari this will print the stats for every 30 seconds.

Upvotes: 5

Shailendra
Shailendra

Reputation: 9102

Depending upon the actual connection pool used ( like dbcp2 etc) in your configuration you can try to set the logging level of the pool package to debug/trace and see if the pool provides this information for you. Typically pools provides this info. Another option you have is that usually the datasource you are using with Spring Boot would be registering itself to JMX as MBeans which has a property "NumActive" along with others like "MaxActive" etc. You can write a timer code in your application which fires at specific time interval , queries the JMX MBean and prints the info in the logs. To check for the available data in MBeans you can hook up VisualVM/JConsole to your app and visit the MBeans tab.

Upvotes: 2

Related Questions