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:

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

Category: Software | Tags: , , Comment »


Leave a Reply



 

Back to top