本文整理汇总了Scala中com.google.common.cache.Cache类的典型用法代码示例。如果您正苦于以下问题:Scala Cache类的具体用法?Scala Cache怎么用?Scala Cache使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Cache类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ResourceCache
//设置package包名称以及导入依赖的类
package se.gigurra.dcs.remote
import java.time.Instant
import com.google.common.cache.CacheBuilder
import com.google.common.cache.Cache
import com.twitter.io.Buf
import scala.collection.concurrent
import scala.collection.JavaConversions._
case class ResourceCache(maxItemsPerCategory: Int) {
private val categories = new concurrent.TrieMap[String, Cache[String, CacheItem]]
def put(category: String, id: String, _data: Buf): Unit = {
val data = Buf.ByteArray.coerce(_data)
categories.getOrElseUpdate(category, newCategory()).put(id, CacheItem(id, data, time))
}
def get(category: String, id: String, maxAgeSeconds: Double): Option[CacheItem] = {
categories.get(category).flatMap(c => Option(c.getIfPresent(id))).filter(_.age <= maxAgeSeconds)
}
def delete(category: String, id: String): Unit = {
categories.get(category).foreach(_.invalidate(id))
}
def getCategory(category: String, maxAgeSeconds: Double): Seq[CacheItem] = {
categories.get(category).map { c =>
c.asMap().values().filter(_.age <= maxAgeSeconds).toSeq
}.getOrElse(Nil)
}
def categoryNames: Seq[String] = {
categories.keys.toSeq
}
private def time: Double = Instant.now.toEpochMilli.toDouble / 1000.0
private def newCategory() = CacheBuilder.newBuilder().maximumSize(maxItemsPerCategory).build[String, CacheItem]()
}
case class CacheItem(id: String, data: Buf, timestamp: Double) {
def age: Double = time - timestamp
private def time: Double = Instant.now.toEpochMilli.toDouble / 1000.0
}