【发布时间】:2014-04-15 11:18:49
【问题描述】:
我有以下从缓存中检索的方法,如果是缓存未命中,则为 RESTfull API。我必须使用flatMap 才能获得一致的界面。
必须将缓存命中的结果包装在 future 中有点困扰我,因为这可能很昂贵(如果库不适合这种用例)。
这东西贵吗?如果是这样,在不使用冗余future 的情况下表达以下内容的组合模式是什么。
abstract class JsonApiQueryWithCache[T: FromResponseUnmarshaller] extends JsonApiQuery[T] {
type fromCacheT = () => Future[Option[T]]
type toCacheT = (T) => Int
def fromCache: fromCacheT
def toCache : toCacheT
override def asCase(): Future[T] = {
fromCache() flatMap (_ match {
// without the nested future: Future[T]
case Some(x) => future {
x
}
// : Future[Future[T]]
case None =>
super.asCase().map{ x=>
toCache(x)
x
}
})
}
}
【问题讨论】:
标签: multithreading scala concurrency parallel-processing future