How to cache results in scala?

前端 未结 5 596
孤街浪徒
孤街浪徒 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条回答
  •  猫巷女王i
    2020-12-31 02:46

    For simple caching needs, I'm still using Guava cache solution in Scala as well. Lightweight and battle tested.

    If it fit's your requirements and constraints generally outlined below, it could be a great option:

    • Willing to spend some memory to improve speed.
    • Expecting that keys will sometimes get queried more than once.
    • Your cache will not need to store more data than what would fit in RAM. (Guava caches are local to a single run of your application. They do not store data in files, or on outside servers.)

    Example for using it will be something like this:

      lazy val cachedData = CacheBuilder.newBuilder()
        .expireAfterWrite(60, TimeUnit.MINUTES)
        .maximumSize(10)
        .build(
          new CacheLoader[Key, Data] {
            def load(key: Key): Data = {
              veryExpansiveDataCreation(key)
            }
          }
        )
    

    To read from it, you can use something like:

      def cachedData(ketToData: Key): Data = {
        try {
          return cachedData.get(ketToData)
        } catch {
          case ee: Exception => throw new YourSpecialException(ee.getMessage);
        }
      }
    

提交回复
热议问题