scalacache 配合 guava

代码

Scala 复制代码
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


  }

}

输出

Scala 复制代码
Getting id 1 from db
A
A
Getting id 1 from db
A
Getting id 2 from db
B
B
B

pom

XML 复制代码
       <!-- 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>
相关推荐
铁锚8 天前
Guava限频器RateLimiter的使用示例
java·高并发·限流·guava·ratelimiter
lingdian2312 天前
限流系列:guava rateLimiter
java·guava·ratelimiter
AcmenSan18 天前
深入解析 Guava Cache
java·spring·guava
技术liul1 个月前
Spring Boot中集成Guava Cache或者Caffeine
spring boot·spring·guava
东阳马生架构2 个月前
Sentinel源码—5.FlowSlot借鉴Guava的限流算法二
算法·sentinel·guava
〆、风神2 个月前
Guava Cache 实战:构建高并发场景下的字典数据缓存
缓存·guava
forestsea3 个月前
Guava:Google开源的Java工具库,太强大了
java·开源·guava
高飞的Leo3 个月前
Guava Cache 中LocalCache的分段锁实现
java·spring·guava
weixin_748877003 个月前
【高并发秒杀系统设计:从Guava到Redis的6级缓存架构演进】
redis·缓存·guava