加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 对于Akka演员来说,安全是否成为关闭不可变状态的方法?

发布时间:2020-12-16 19:09:00 所属栏目:安全 来源:网络整理
导读:这里的目的是为一个需要调用外部服务(或一些昂贵但高度可缓存的操作)的actor实现非常简单的缓存,而不使用可变状态. class A extends Actor{ def receive = { case GetCommand = val response = callExternalService() context.become(receiveWithCache(respo
这里的目的是为一个需要调用外部服务(或一些昂贵但高度可缓存的操作)的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
  }
}

我知道有更多的高级实现方法,其中一个完全成熟的CacheSystem可以在Akka模式页面中找到,但在某些情况下,这并不是必需的.

此外,有趣的是,如果使用成为这样安全的话,知道答案.

解决方法

据我所知,这种技术是健全的,应该对您有好处.它实际上是一个更聪明的方法来避免在你的代码中有一个可变的var响应.我在一个答案 here中采用了这种技术,而Akka队的Viktor似乎认为这是一个很好的解决方案.有一件事,你可以改变:

def receiveWithCache(cachedResponse:R): PartialFunction[Any,Unit] = {
  case GetCommand => sender ! cachedResponse
  case InvalidateCache => context.unbecome
}

至:

def receiveWithCache(cachedResponse:R): Receive = {
  case GetCommand => sender ! cachedResponse
  case InvalidateCache => context.unbecome
}

接收类型是PartialFunction [Any,Unit]的缩写别名.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读