Skip to content

Instantly share code, notes, and snippets.

@cb372
Created April 23, 2014 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cb372/11200131 to your computer and use it in GitHub Desktop.
Save cb372/11200131 to your computer and use it in GitHub Desktop.
Simple examples of using ScalaCache in a webapp, using Memcached for caching
package sample
import scalacache._
import memoization._
import memcached._
import scala.concurrent.duration._
import scala.language.postfixOps
case class User(id: Int, name: String)
trait DB {
def findUserById(id: Int): Option[User]
}
/*
* Example of using ScalaCache to cache a DB lookup
*/
class UserRepository(db: DB)(implicit val scalaCache: ScalaCache) {
def find(userId: Int): Option[User] = memoize(30 minutes) {
db.findUserById(userId)
}
}
/*
* Example of using ScalaCache to cache a rendered view
*/
class Controller(implicit val scalaCache: ScalaCache) {
// Index page will be cached for 60 seconds
def index = {
withCaching("/index", Some(60 seconds)) {
// Lookup a bunch of stuff in DBs and external APIs...
// Render the view...
render("index.ssp")
}
}
private def render(template: String): String = ???
}
object MyApp {
implicit val scalaCache = ScalaCache(MemcachedCache("cacheserver:11211"))
val db = new DB {
def findUserById(id: Int) = ??? // do DB lookup
}
val userRepo = new UserRepository(db)
val userController = new Controller
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment