rei*_*kje 2 aop caching scala python-decorators
头脑风暴:我正在开发一个Scala项目,我们在那里进行服务调用,需要使用memcache缓存返回值.我正在研究一个Python项目,该项目使用装饰器来注释应该缓存返回值的函数.我在Scala中寻找一种类似的方法来为函数添加缓存方面.
可以说我有这个功能,def callingService(arg1: String, arg2: Int): String我想
任何调用callingService的代码都不应该知道缓存.callingService的实现应该只调用服务X并返回一个String值而不处理缓存内容.
我更喜欢Stackable Trait Pattern和Cake Pattern:
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)
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
val service = new Service with ServiceCache with MapCache[(String, Int), String]
Run Code Online (Sandbox Code Playgroud)
当然,您可以实现自己的缓存策略,并在创建服务时与其混合使用