简体   繁体   中英

Playframework 1.2.5 and JDBI

I am trying to use JDBI with Play 1.2.5 and im having a problem with running out of database connections. I am using the H2 in-memory database (in application.conf, db=mem)

I have created class to obtain jdbi instances that uses Play's DB.datasource like so:

public class Database {      
    private static DataSource ds = DB.datasource;

    private static DBI getDatabase() {       
        return new DBI(ds);       
    }

    public static <T> T withDatabase(HandleCallback<T> hc) {
        return getDatabase().withHandle(hc);       
    }

    public static <T> T withTransaction(TransactionCallback<T> tc) {
        return getDatabase().inTransaction(tc);
    }
}

Every time I do a database call, a new DBI instance is created but it always wraps the same static DataSource object (play.db.DB.datasource)

Whats happening is, after a while I am getting the following:

CallbackFailedException occured : org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException: java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.

I am confused because the whole point of DBI.withHandle() and DBI.withTransaction() is to close the connection and free up resources when the callback method completes.

I also tried making getDatabase() return the same DBI instance every time, but the same problem occured.

What am I doing wrong?

Duh. Turns out I was leaking connections in some old code that wasn't using withHandle(). As soon as I upgraded it the problem stopped

From the official documentation

Because Handle holds an open connection, care must be taken to ensure that each handle is closed when you are done with it. Failure to close Handles will eventually overwhelm your database with open connections, or drain your connection pool.

Turns out you are not guaranteeing the closing of the handle in your callback function whenever it is provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM