这里的目的是为需要调用外部服务(或一些昂贵但高度可缓存的操作)的actor实现一个非常简单的缓存,而不使用可变状态.
class A extends Actor{
def receive = {
case GetCommand =>
val response = callExternalService()
context.become(receiveWithCache(response))
context.system.scheduler.schedule(1 day, 1 day, self, InvalidateCache)
sender ! response
}
def receiveWithCache(cachedResponse:R): PartialFunction[Any,Unit] = {
case GetCommand => sender ! cachedResponse
case InvalidateCache => context.unbecome
}
}
Run Code Online (Sandbox Code Playgroud)
我知道有更多高级方法可以实现这一点,其中包括可以在Akka模式页面中找到的完全成熟的CacheSystem,但在某些情况下确实不需要.
另外,如果使用变得像这样安全,知道答案是有趣的.
cmb*_*ter 13
据我所知,这种技术很健全,应该对你有好处.它实际上是一种更聪明的方法,可以var response
在代码中使用mutable .我在这里的答案中恰巧使用了这种技术,来自Akka团队的Viktor似乎认为这是一个很好的解决方案.但有一点,你可以改变:
def receiveWithCache(cachedResponse:R): PartialFunction[Any,Unit] = {
case GetCommand => sender ! cachedResponse
case InvalidateCache => context.unbecome
}
Run Code Online (Sandbox Code Playgroud)
至:
def receiveWithCache(cachedResponse:R): Receive = {
case GetCommand => sender ! cachedResponse
case InvalidateCache => context.unbecome
}
Run Code Online (Sandbox Code Playgroud)
该Receive
类型是一个速记别名PartialFunction[Any,Unit]
.