databasegrailsgrails-2.2

efficient way to check database connection?


What is the fastest database connection check in grails? I need to create an endpoint which will be called again and again by a script so this needs to be efficient. The database goes down fom time to time and this script will call this api that will return a status code. Based on this status code the bot will know the database is down. If it is 200 then everything is ok.

So i need to check if database connection is intact in a very efficient manner. Since the call happens every few seconds what is the fastest way to check for database status. My thought is to use a simple gorm query like Status.read(1). If there is an exception then return a non 200 status code. Is there a more efficient way for a quick database status check?

I appreciate any insights. I am using Grails 2.2.


Solution

  • Why not just avoid using GORM all together and just use a super simple database query like SELECT 1? Putting this into a service it might look like something like this:

    package my.example
    
    class MyService {
    
        def dataSource
        def someTimeoutValue = 1000
    
        boolean isDatabaseThere() {
            try {
                dataSource.connection.isValid(someTimeoutValue)
                return true // everything is okay
            } catch (Exception e) {
                return false // everything is not okay
            }
        }
    }
    

    Pardon any typos or anything, that was written on the fly.