Skip to content
Advertisement

How can you find out from spring cloud function that the connection you established to the database is closed?

In a spring cloud function usage, you don’t want your database connection to keep existing in the database. Once the spring cloud function finishes its process, is the following way to close the function appropriate?

   HikariDataSource ds = (HikariDataSource) applicationContext.getBean(HikariDataSource.class);
        if (ds != null) {
        ds.close();
}

How do we validate if the spring cloud function inherently closes the connection even if we don’t do the implementation above? I saw the log below indicating that the connection pool is closed, but also that the database keeps growing its connections, indicating that connections are not properly closed. How do we make sure the connections are closed after spring cloud function implementation is finished?

INFO 22336 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
INFO 22336 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Advertisement

Answer

Closing the hikari pool in a lambda function explicitly had helped. Spring is closing the connection but the lambda shuts down immediately for which the RDS is not able to close the connection properly.

It’s better to have the lambda functions simple and not packaged with multiple functions in a single repo. After a lambda executes, one can close the connection as in the below example. Closing the datasource inherently closes the connection. I’m not sure why we need to close it explicitly and still would like to expect spring to close the connection properly but this worked.

if (yourDatasource != null) {
    yourDatasource .close();
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement