Setting MySQL Load Balancing in Play and Scala
In my previous post I showed a way to set MySQL load balancing with Java and Spring.
To make your queries go to the slave database, you need to set connection to read-only. In Play Framework 2.0 with Scala, this can’t be simpler:
1 2 3 4 5 6 7 8 9 10 11 12 | def withReadOnlyConnection[A](block : Connection = > A)( implicit app : Application) : A = { DB.withConnection { connection = > try { connection.setAutoCommit( false ) connection.setReadOnly( true ) block(connection) } finally { connection.setReadOnly( false ) } } } |
Now you can just wrap your database code as:
1 2 3 4 5 6 | withReadOnlyConnection[Option[User]] { implicit connection : Connection = > SQL(....) etc, etc. } |
For additional info on Play and Anorm see: Anorm, simple SQL data access