0

I was wondering how is the right way to manage Slick 3 (3.0.0-RC3 at this moment) database instances in a Play Framework 2.3.x application. According to the upgrade guide, each instance has a connection pool associated.

My guess is that I should handle a single instance of each real database in the entire application, instead of creating an instance per database operation (like this example), because the latter implies to also create a pool for each operation. If I follow the example and do this:

object Thing {
  private def db: Database = Database.forConfig("mydb")

  private val things = TableQuery[Thing]

  def getAll = {
    val curDb = db
    try curDb.run(things.result)
    finally curDb.close
  }
}

I end up creating a pool, which creates 10 connections to the database per execution of the getAll function, and disposing them after a single query.

However, if I manage the instance as a singleton, I am not sure if it is thread safe, and can be safely used by the many threads that a Play application manages.

This is my database configuration in application.conf:

mydb= {
  dataSourceClass = org.postgresql.ds.PGSimpleDataSource
  connectionTestQuery="SELECT 1"
  properties = {
    databaseName = "mydb"
    user = "postgres"
    password = "postgres"
    serverName = "localhost"
  }
  numThreads = 10
  connectionPool = HikariCP
}

I'm using HikariCP-java6 v2.0.1.

Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116

2 Answers2

1

Do not create and destroy pools after each query. That is going be a disaster. HikariCP is thread-safe. Though I would suggest, if possible, running the latest (2.3.6).

brettw
  • 10,664
  • 2
  • 42
  • 59
1

I still have several questions about what the best practices are but I think if you change

private def db: Database = Database.forConfig("mydb")

to

private val db: Database = Database.forConfig("mydb")

Notice the change from def to val.

That should eliminate the creation of a new connection pool for each query.

AlphaGeek
  • 383
  • 2
  • 11