How to cache results in scala?

前端 未结 5 593
孤街浪徒
孤街浪徒 2020-12-31 01:51

This page has a description of Map\'s getOrElseUpdate usage method:

object WithCache{
  val cacheFun1 = collection.mutable.Map[Int, Int]()
  def         


        
5条回答
  •  心在旅途
    2020-12-31 02:28

    Take a look at spray caching (super simple to use)

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

    makes the job easy and has some nice features

    for example :

          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")
            }
          }
    

提交回复
热议问题