Created
May 12, 2017 16:08
-
-
Save JoolsF/b4604a62801071195dc2cfc7535b40c1 to your computer and use it in GitHub Desktop.
Scala cache using Guava. Simple example.
This file contains 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
import scalacache._ | |
import guava._ | |
import memoization._ | |
import com.google.common.cache.CacheBuilder | |
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration._ | |
object TestApp extends App { | |
val underlyingGuavaCache = CacheBuilder.newBuilder().maximumSize(10000L).build[String, Object] | |
implicit val scalaCache = ScalaCache(GuavaCache(underlyingGuavaCache)) | |
val db = Map(1 -> "A", 2 -> "B", 3 -> "C") | |
def queryDb(id: Int): String = { | |
println(s"Getting id $id from db") | |
db(id) | |
} | |
def getUser(id: Int): Future[String] = memoize(30 days) { | |
Future { | |
queryDb(id) | |
} | |
} | |
getUser(1) | |
Thread.sleep(100) | |
getUser(1) | |
Thread.sleep(100) | |
getUser(1) | |
Thread.sleep(100) | |
getUser(2) | |
Thread.sleep(100) | |
getUser(2) | |
Thread.sleep(100) | |
getUser(2) | |
Thread.sleep(100) | |
// Output - Only hits 'db' once | |
// Getting id 1 from db | |
// Getting id 2 from db | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment