代码
package com.yy.guavaimport scalacache._
import scalacache.guava._
import scalacache._
import scalacache.guava._
import com.google.common.cache.CacheBuilder
import scalacache.modes.sync._
import scalacache.serialization.binary._
import scalacache._
import guava._
import memoization._import com.google.common.cache.CacheBuilderimport scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import java.time.Instant/*** scala套壳的框架. 支持 guava caffeine 作为底层实现.* https://cb372.github.io/scalacache/* https://cb372.github.io/scalacache/docs/cache-implementations.html
*/
object scalaCacheDemo1 {def main(args: Array[String]): Unit = {val underlyingGuavaCache = CacheBuilder.newBuilder().maximumSize(1000L) // 配置缓存个数.build[String, Entry[String]]implicit val guavaCache: Cache[String] = 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)}/*https://cb372.github.io/scalacache/docs/memoization.html配置缓存时长*/def getUser(id: Int): String = memoizeSync(Option(1.seconds)) {queryDb(id)}println(getUser(1))Thread.sleep(100)println(getUser(1))Thread.sleep(2000)println(getUser(1))Thread.sleep(100)println(getUser(2))Thread.sleep(100)println(getUser(2))Thread.sleep(100)println(getUser(2))Thread.sleep(100)// Output - Only hits 'db' once// Getting id 1 from db// Getting id 2 from db}}
输出
Getting id 1 from db
A
A
Getting id 1 from db
A
Getting id 2 from db
B
B
B
pom
<!-- https://mvnrepository.com/artifact/com.github.cb372/scalacache-core --><dependency><groupId>com.github.cb372</groupId><artifactId>scalacache-core_${scala.binary.version}</artifactId><version>${scalacache.version}</version></dependency><!-- https://mvnrepository.com/artifact/com.github.cb372/scalacache-guava --><dependency><groupId>com.github.cb372</groupId><artifactId>scalacache-guava_${scala.binary.version}</artifactId><version>${scalacache.version}</version></dependency>