当前位置: 首页>>代码示例>>Scala>>正文


Scala CacheBuilder类代码示例

本文整理汇总了Scala中com.google.common.cache.CacheBuilder的典型用法代码示例。如果您正苦于以下问题:Scala CacheBuilder类的具体用法?Scala CacheBuilder怎么用?Scala CacheBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了CacheBuilder类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
} 
开发者ID:GiGurra,项目名称:dcs-remote2,代码行数:47,代码来源:ResourceCache.scala

示例2: InMemoryGCMMessageStoreImpl

//设置package包名称以及导入依赖的类
package io.grhodes.mcm.server.gcm

import java.util

import com.google.common.cache.CacheBuilder
import com.typesafe.config.ConfigFactory

class InMemoryGCMMessageStoreImpl extends GCMMessageStore {
  private val ServerConfig = ConfigFactory.load().getConfig("io.grhodes.mcm-server.xmpp")

  private val StoredMessages = CacheBuilder.newBuilder().maximumSize(1000).build[String, String]()
  private val isActive = new util.concurrent.atomic.AtomicBoolean(ServerConfig.getBoolean("message.store.enabled"))

  override def shutdown(): Unit = {}

  override def storeMessage(regId: String, message: String): Boolean = {
    if(isActive.get()) {
      StoredMessages.put(regId, message)
      true
    } else {
      false
    }
  }
} 
开发者ID:grahamar,项目名称:mcm-server,代码行数:25,代码来源:InMemoryGCMMessageStoreImpl.scala

示例3: GuavaConfiguration

//设置package包名称以及导入依赖的类
package edu.cmsandiga.examples.caching

import java.util.concurrent.TimeUnit

import com.google.common.cache.CacheBuilder
import org.springframework.cache.guava.GuavaCacheManager
import org.springframework.context.annotation.{Bean, Configuration}

@Configuration
class GuavaConfiguration {

  @Bean
  def guavaCache() ={
    val cacheManager = new GuavaCacheManager()
    cacheManager.setCacheBuilder(
      CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).maximumSize(100)
    )
    cacheManager
  }

} 
开发者ID:cmsandiga,项目名称:Spring-boot-scala,代码行数:22,代码来源:GuavaConfiguration.scala

示例4: AuthServiceImpl

//设置package包名称以及导入依赖的类
package com.bwsw.tstreamstransactionserver.netty.server.authService

import com.bwsw.tstreamstransactionserver.options.ServerOptions.AuthOptions
import com.google.common.cache.CacheBuilder
import org.slf4j.{Logger, LoggerFactory}


class AuthServiceImpl(authOpts: AuthOptions) {
  private val logger: Logger = LoggerFactory.getLogger(this.getClass)

  private val random = scala.util.Random
  private val usersToken = CacheBuilder.newBuilder()
    .maximumSize(authOpts.activeTokensNumber)
    .expireAfterAccess(authOpts.tokenTTL, java.util.concurrent.TimeUnit.SECONDS)
    .build[java.lang.Integer, String]()

  private[server] final def authenticate(authKey: String): Int = {
    if (authKey == authOpts.key) {
      val token = random.nextInt(Integer.MAX_VALUE)
      usersToken.put(token, authKey)
      if (logger.isDebugEnabled()) logger.debug(s"Client with authkey $authKey is successfully authenticated and assigned token $token.")
      token
    } else {
      if (logger.isDebugEnabled()) logger.debug(s"Client with authkey $authKey isn't authenticated and assigned token -1.")
      -1
    }
  }

  private[server] final def isValid(token: Int): Boolean = {
    val isValid = token != -1 && usersToken.getIfPresent(token) != null
    if (logger.isDebugEnabled())
      if (isValid) logger.debug(s"Client token $token is accepted.")
      else logger.debug(s"Client token $token is expired or doesn't exist.")
    isValid
  }
} 
开发者ID:bwsw,项目名称:tstreams-transaction-server,代码行数:37,代码来源:AuthServiceImpl.scala

示例5: Server

//设置package包名称以及导入依赖的类
package com.twitter.finagle.kestrel

import _root_.java.net.SocketAddress
import _root_.java.util.concurrent.{BlockingDeque, LinkedBlockingDeque}
import com.google.common.cache.{CacheBuilder, CacheLoader}
import com.twitter.finagle.builder.{Server => BuiltServer, ServerBuilder}
import com.twitter.finagle.{ServiceFactory, ClientConnection}
import com.twitter.util.{Future, Time}
import org.jboss.netty.buffer.ChannelBuffer
import protocol.{Kestrel, Command, Response}

class Server(address: SocketAddress) {
  private[this] val serviceFactory = new ServiceFactory[Command, Response] {

    private[this] val queues = CacheBuilder.newBuilder()
      .build(new CacheLoader[ChannelBuffer, BlockingDeque[ChannelBuffer]] {
        def load(k: ChannelBuffer) = new LinkedBlockingDeque[ChannelBuffer]
      })

    def apply(conn: ClientConnection) = Future.value(new InterpreterService(new Interpreter(queues)))
    def close(deadline: Time) = Future.Done
  }

  private[this] val serverSpec =
    ServerBuilder()
      .name("schmestrel")
      .codec(Kestrel())
      .bindTo(address)

  private[this] var server: Option[BuiltServer] = None

  def start(): BuiltServer = {
    server = Some(serverSpec.build(serviceFactory))
    server.get
  }

  def stop() {
    require(server.isDefined, "Server is not open!")

    server.foreach { server =>
      server.close()
      this.server = None
    }
  }
} 
开发者ID:deenar,项目名称:fintest,代码行数:46,代码来源:Server.scala

示例6: TimedCache

//设置package包名称以及导入依赖的类
package webby.commons.cache

import java.util.concurrent.TimeUnit
import java.{lang => jl}

import com.google.common.cache.{CacheBuilder, CacheLoader, LoadingCache}


abstract class TimedCache[K, RealK, V](val cache: LoadingCache[RealK, V]) {
  def get(key: K): V = cache.get(transformKey(key))

  def invalidate(key: K): Unit = cache.invalidate(transformKey(key))
  def refresh(key: K): Unit = cache.refresh(transformKey(key))

  protected def transformKey(key: K): RealK
}

object TimedCache {

  def default[K <: AnyRef, V <: AnyRef](expireDuration: Long, expireUnit: TimeUnit)(cacheLoader: K => V): TimedCache[K, K, V] =
    new TimedCache[K, K, V](
      CacheBuilder.newBuilder().expireAfterWrite(expireDuration, expireUnit).build(new CacheLoader[K, V] {
        def load(key: K): V = cacheLoader(key)
      })) {
      protected def transformKey(key: K): K = key
    }

  def intKey[V <: AnyRef](expireDuration: Long, expireUnit: TimeUnit)(cacheLoader: Int => V): TimedCache[Int, jl.Integer, V] =
    new TimedCache[Int, jl.Integer, V](
      CacheBuilder.newBuilder().expireAfterWrite(expireDuration, expireUnit).build(new CacheLoader[jl.Integer, V] {
        def load(key: jl.Integer): V = cacheLoader(key)
      })) {
      protected def transformKey(key: Int): Integer = key
    }

  def stringKey[V <: AnyRef](expireDuration: Long, expireUnit: TimeUnit)(cacheLoader: String => V): TimedCache[String, String, V] =
    default[String, V](expireDuration, expireUnit)(cacheLoader)
} 
开发者ID:citrum,项目名称:webby,代码行数:39,代码来源:TimedCache.scala

示例7: OnlyOnceCache

//设置package包名称以及导入依赖的类
package webby.commons.cache

import java.util.concurrent.TimeUnit

import com.google.common.cache.CacheBuilder
import webby.commons.concurrent.LockSet


case class OnlyOnceCache[Req <: AnyRef, Resp <: AnyRef, LockKey <: AnyRef](expireDuration: Long,
                                                                           expireUnit: TimeUnit,
                                                                           lockStripes: Int = 32,
                                                                           maximumSize: Long = 1000L) {
  private val lockSet = LockSet.lock[LockKey](lockStripes)

  private val cache = CacheBuilder.newBuilder()
    .expireAfterWrite(expireDuration, expireUnit)
    .maximumSize(maximumSize)
    .build[LockKey, (Req, Resp)]()

  def action(req: Req, getKey: Req => LockKey)(body: Req => Resp, onCached: Resp => Resp = a => a): Resp = {
    val lockKey: LockKey = getKey(req)
    lockSet.withLock(lockKey) {
      val cached: (Req, Resp) = cache.getIfPresent(lockKey)
      if (cached != null && cached._1 == req) onCached(cached._2)
      else {
        val result = body(req)
        cache.put(lockKey, req -> result)
        result
      }
    }
  }
} 
开发者ID:citrum,项目名称:webby,代码行数:33,代码来源:OnlyOnceCache.scala

示例8: GuavaCacheTest

//设置package包名称以及导入依赖的类
package com.twitter.cache.guava

import com.google.common.cache.{CacheLoader, CacheBuilder}
import com.twitter.cache.AbstractFutureCacheTest
import com.twitter.util.{Future, Promise}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class GuavaCacheTest extends AbstractFutureCacheTest {
  def name: String = "GuavaCache"

  def mkCtx(): Ctx = new Ctx {
    val guava = CacheBuilder.newBuilder().build[String, Future[String]]()
    val cache = new GuavaCache[String, String](guava)
  }

  def mkCache() =
    CacheBuilder
      .newBuilder()
      .build(
        new CacheLoader[String, Future[Int]] {
          override def load(k: String): Future[Int] = new Promise[Int]
        }
      )

  test("GuavaCache#fromLoadingCache is interrupt safe") {
    val fCache = GuavaCache.fromLoadingCache(mkCache())
    interruptSafe(fCache)
  }

  test("GuavaCache#fromCache is interrupt safe") {
    val fCache = GuavaCache.fromCache((_:String) => new Promise[Int], mkCache())
    interruptSafe(fCache)
  }
} 
开发者ID:lanshuijuntuan,项目名称:Java.util,代码行数:37,代码来源:GuavaCacheTest.scala

示例9: LoadingFutureCacheTest

//设置package包名称以及导入依赖的类
package com.twitter.cache.guava

import com.google.common.cache.{CacheLoader, CacheBuilder}
import com.twitter.cache.AbstractLoadingFutureCacheTest
import com.twitter.util.Future
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class LoadingFutureCacheTest extends AbstractLoadingFutureCacheTest {

  def name: String = "LoadingFutureCache (guava)"

  // NB we can't reuse AbstractFutureCacheTest since
  // loading cache semantics are sufficiently unique
  // to merit distinct tests.

  def mkCtx: Ctx = new Ctx {
    val cache = new LoadingFutureCache(
      CacheBuilder
        .newBuilder()
        .build(
          new CacheLoader[String,Future[Int]] {
            override def load(k: String): Future[Int] = {
              cacheLoaderCount += 1
              Future.value(k.hashCode)
            }
          }
        )
    )
  }
} 
开发者ID:lanshuijuntuan,项目名称:Java.util,代码行数:33,代码来源:LoadingFutureCacheTest.scala


注:本文中的com.google.common.cache.CacheBuilder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。