Setting MySQL Load Balancing in Play and Scala
April 11th, 2012 — 1:34pm
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:
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:
withReadOnlyConnection[Option[User]] { implicit connection: Connection => SQL(....) etc, etc. }
For additional info on Play and Anorm see: Anorm, simple SQL data access