如何在scala中缓存结果?

Jer*_*iho 21 caching scala

此页面描述了Map的getOrElseUpdate使用方法:

object WithCache{
  val cacheFun1 = collection.mutable.Map[Int, Int]()
  def fun1(i:Int) = i*i
  def catchedFun1(i:Int) = cacheFun1.getOrElseUpdate(i, fun1(i))
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用catchedFun1哪个将检查是否cacheFun1包含与之关联的键和返回值.否则,它将调用fun1,然后缓存fun1结果cacheFun1,然后返回fun1结果.

我可以看到一个潜在的危险 - cacheFun1可能变得很大.所以cacheFun1必须通过垃圾收集器以某种方式清理?

PS怎么样scala.collection.mutable.WeakHashMap and java.lang.ref.*

olu*_*ies 16

请参阅所述论文的备注模式Scalaz实现.

还可以查看一下STM实现,例如Akka.

并不是说这只是本地缓存,所以你可能想要查看分布式缓存或STM,如CCSTM,TerracottaHazelcast

  • @Debilski取决于"缓存"要求.在这种情况下,"弱缓存"可以提升海报关注"cacheFun1可能[太大]". (2认同)

Nim*_*007 8

看看喷雾缓存(超级简单易用)

http://spray.io/documentation/1.1-SNAPSHOT/spray-caching/

使工作变得轻松,并具有一些很好的功能

例如 :

      import spray.caching.{LruCache, Cache}

      //this is using Play for a controller example getting something from a user and caching it
      object CacheExampleWithPlay extends Controller{

        //this will actually create a ExpiringLruCache and hold data for 48 hours
        val myCache: Cache[String] = LruCache(timeToLive = new FiniteDuration(48, HOURS))

        def putSomeThingInTheCache(@PathParam("getSomeThing") someThing: String) = Action {
          //put received data from the user in the cache
          myCache(someThing, () => future(someThing))
          Ok(someThing)
        }

        def checkIfSomeThingInTheCache(@PathParam("checkSomeThing") someThing: String) = Action {
          if (myCache.get(someThing).isDefined)
            Ok(s"just $someThing found this in the cache")
          else
            NotFound(s"$someThing NOT found this in the cache")
        }
      }
Run Code Online (Sandbox Code Playgroud)


Deb*_*ski 6

在斯卡拉的邮件列表,他们有时会指向地图制作工具谷歌集合库.你可能想看一下.

  • Google Collections已重命名为Guava,新的CacheBuilder可能更接近:http://docs.guava-libraries.googlecode.com/git/javadoc/index.html?com/google/common/cache/CacheBuilder. HTML (4认同)