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

在scala中实施长时间的投票,并与akka一起玩2.0

发布时间:2020-12-16 09:14:46 所属栏目:安全 来源:网络整理
导读:我在潜在的分布式环境中在Play 2.0中实施长时间轮询.我理解的方式是,当Play获得请求时,它应该挂起更新的待处理通知,然后转到数据库获取新数据并重复.我开始关注Play 2.0提供的聊天示例,但它在websocket中.此外,它看起来不像分发的能力.所以我以为我会用Akka
我在潜在的分布式环境中在Play 2.0中实施长时间轮询.我理解的方式是,当Play获得请求时,它应该挂起更新的待处理通知,然后转到数据库获取新数据并重复.我开始关注Play 2.0提供的聊天示例,但它在websocket中.此外,它看起来不像分发的能力.所以我以为我会用Akka的事件巴士.我采取了事件流实现,并通过LookupClassification复制了我自己的.不过,我很遗憾,我将如何收到一条消息(或者说是什么应该是用户而不是ActorRef)?

EventStream实现:
https://github.com/akka/akka/blob/master/akka-actor/src/main/scala/akka/event/EventStream.scala

解决方法

我不知道这是你正在寻找的,但是在彗星样本中有一个简单的解决方案,您可以适应使用AKKA演员.它使用无限iframe而不是长轮询.我已经使用了一个适应版本的更复杂的应用程序做多个数据库调用和长时间的计算在AKKA演员,它的工作正常.

def enum = Action {
    //get your actor
    val myActorRef = Akka.system.actorOf(Props[TestActor]) 

   //do some query to your DB here. Promise.timeout is to simulate a blocking call
   def getDatabaseItem(id: Int): Promise[String] = { Promise.timeout("test",10 milliseconds) } 

    //test iterator,you will want something smarter here
    val items1 = 1 to 10 toIterator

    // this is a very simple enumerator that takes ints from an existing iterator (for an http request parameters for instance) and do some computations
    def myEnum(it: Iterator[Int]): Enumerator[String] = Enumerator.fromCallback[String] { () =>
      if (!items1.hasNext)
        Promise.pure[Option[String]](None) //we are done with our computations
      else {

        // get the next int,query the database and compose the promise with a further query to the AKKA actor
        getDatabaseItem(items1.next).flatMap { dbValue =>
          implicit val timeout = new Timeout(10 milliseconds)
          val future = (myActorRef ? dbValue) mapTo manifest[String]

          // here we convert the AKKA actor to the right Promise[Option] output
          future.map(v => Some(v)).asPromise
        }
      }
    }

    // finally we stream the result to the infinite iframe. 
    // console.log is the javascript callback,you will want something more interesting.
    Ok.stream(myEnum(items1) &> Comet(callback = "console.log"))
  }

请注意,这个fromCallback不允许您将枚举器与“andThen”组合,在中继版本的play2中,如果要使用组合,则可能更适合于generateM方法.

轮询时间不长,但工作正常.

(编辑:李大同)

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

    推荐文章
      热点阅读