Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you implement a caching aspect in Scala

Brainstorming: I am working on a Scala project where we do service calls and need to cache the return values using memcache. I was working on a Python project that used decorators to annotate the functions whose return values should be cached. I am looking for a similar way in Scala to add a caching aspect to a function.

Lets say I have this function def callingService(arg1: String, arg2: Int): String I want to

  • compute a cache key based on the function name and arguments
  • if the cache doesn't contain the key do the service call
  • serialize the return value and store it in the cache
  • otherwise deserialize the cached value and return it

Any code that invokes callingService should not know about caching. The implementation of callingService should just call service X and return a String value and not deal with caching stuff.

like image 279
reikje Avatar asked Dec 29 '25 23:12

reikje


1 Answers

I prefer Stackable Trait Pattern and Cake Pattern for that:

class Service {
  def callingService(arg1: String, arg2: Int): String = "ok"
}

trait Memo[K, V] {
  def cache(k: K)(v : => V): V
}

trait ServiceCache extends Service {
  self : Memo[(String, Int), String] =>

  abstract override def callingService(arg1: String, arg2: Int): String =
    cache((arg1, arg2)) { super.callingService(arg1, arg2) }
}

trait MapCache[K, V] extends Memo[K, V] {
  private val _cache = new collection.mutable.HashMap[K, V]
  def cache(k: K)(v : => V): V = _cache.getOrElseUpdate(k, v)
}

using example:

val service = new Service with ServiceCache with MapCache[(String, Int), String]

and of course you can implement own Caching strategy and mix with it at the moment of service creation

like image 199
Yuriy Avatar answered Jan 01 '26 16:01

Yuriy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!