yankov
8/8/2014 - 5:08 PM

postgres async connection pool

postgres async connection pool

  val poolConfiguration = new PoolConfiguration(
    maxIdle = 1000,
    maxObjects = 5,
    maxQueueSize = 5,
    validationInterval = 1000
  )

  val factory = new PostgreSQLConnectionFactory(configuration)
  val pool = new SingleThreadedAsyncObjectPool[PostgreSQLConnection](factory, poolConfiguration)

  def withConnection[T](fn: PostgreSQLConnection => Future[T]): Future[T] = {
    val conn = Await.result(pool.take, 5 seconds)
    val f = fn(conn)
    f.onComplete{ case _ =>  pool.giveBack(conn) }
    f
  }

  def sendQuery(query: String): Future[QueryResult] = withConnection { conn => {
      conn.sendQuery(query)
  }}