28

Is there an easy way to use a DB connection pool with scala's Slick?

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
  • My guess is that if you use it from within the Play Framework 2.1 you get connection pooling for free. Play Framework uses [BoneCP](http://jolbox.com/) as it's underlying library – EECOLOR Mar 20 '13 at 22:00
  • Similar question: [Scala connection pool library?](http://stackoverflow.com/questions/5080707/scala-connection-pool-library) – EECOLOR Mar 21 '13 at 08:00
  • 1
    I'm not asking **if** there is a pooling library in the JVM world. I'm asking about the easiest way to use (any) one with Slick. Thanks – Pablo Fernandez Mar 21 '13 at 13:56
  • Slick requires a session to be available. You could get one from the database object `Database.forDataSource(ds: DataSource)`. You can use the `createSession` or `withSession` methods from the database object. The datasource is the one you request from a pool library. – EECOLOR Mar 21 '13 at 14:15

4 Answers4

28

I use Apache Commons DBCP for this. Basically, you simply create a DataSource, that encapsulates the pooling details, and pass that DataSource to Slick:

import org.apache.commons.dbcp.BasicDataSource

val dataSource: DataSource = {
  val ds = new BasicDataSource
  ds.setDriverClassName("org.hsqldb.jdbc.JDBCDriver")
  ds.setUsername("SA")
  ds.setPassword("")
  ds.setMaxActive(20);
  ds.setMaxIdle(10);
  ds.setInitialSize(10);
  ds.setValidationQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS")
  new java.io.File("target").mkdirs // ensure that folder for database exists
  ds.setUrl("jdbc:hsqldb:file:target/db/db")
  ds
}

// test the data source validity
dataSource.getConnection().close()

// get the Slick database that uses the pooled connection
val database = Database.forDataSource(dataSource)

This example uses HSQLDB, but can be easily adapted to any other database.

Full example is here (you can clone the project, and run sbt run in lift/ directory to see it working).

Rogach
  • 26,050
  • 21
  • 93
  • 172
22

For completion I ended up writing a blog post about this:

http://fernandezpablo85.github.io/2013/04/07/slick_connection_pooling.html

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
1

Play 2.4 now uses HikariCP which looks really nice: https://brettwooldridge.github.io/HikariCP/ https://www.playframework.com/documentation/2.4.x/SettingsJDBC

nemoo
  • 3,269
  • 4
  • 38
  • 51
-1

It appears as though the later version of play pool configured connections - see http://www.playframework.com/documentation/2.0.1/SettingsJDBC

Michael Nash
  • 103
  • 4