Created
April 23, 2014 01:35
-
-
Save cb372/11200131 to your computer and use it in GitHub Desktop.
Simple examples of using ScalaCache in a webapp, using Memcached for caching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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