scalacache 配合 guava

代码

package com.yy.guava

import 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.CacheBuilder

import 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

       
        
            com.github.cb372
            scalacache-core_${scala.binary.version}
            ${scalacache.version}
        
        
        
            com.github.cb372
            scalacache-guava_${scala.binary.version}
            ${scalacache.version}
        

你可能感兴趣的:(free,guava)