Scala Akka Actors:如何将Http响应的结果发送回发送者?

问题描述

我正在尝试在Akka Actor中执行以下Scala代码。

class FilteringService(implicit timeout: Timeout) extends Actor {

  def receive: PartialFunction[Any,Unit] = {

    case GetProfiles ⇒
      val requester = sender
      def getProfiles = {

        var result = new Array[Profile](0)

        println("[GET-PROFILES] Entered,making request")
        val req = Get("http://localhost:9090/profiles")
        implicit val profileFormat = jsonFormat16(Profile)


        val responseFuture: Future[HttpResponse] = Http().singleRequest(req)
        println("[GET-PROFILES] Entered,request sent")
        responseFuture.onComplete {

          case Success(response) =>
            println("[RES - SUCCESS] Request returned with " + response.status)
            val responseAsProfiles =  Unmarshal(response.entity).to[Array[Profile]]
            responseAsProfiles.onComplete {
            println("[UNMARSH - SUCCESS] Unmarshaling Done!")
            _.get match {
              case profiles: Array[Profile] =>
                println("[UNMARSH - SUCCESS] Sending Profiles message to " + sender())
                requester ! profiles
                println("[UNMARSH - SUCCESS] Message sent to " + sender())
              case _ => println("error")
              }
            }

          case Failure(_)   =>
            sys.error("something wrong")
            //return Future[Array[Profile]]

        }
      }
      println("[RECEIVE] Message GetProfiles received from " + sender().toString())
      getProfiles
      println("[RECEIVE] Message GetProfiles invoked")

  }

Actor收到消息“ GetProfiles”时:

1-它向远程服务器发送请求,所以操作的结果是Future [HttpResponse]

2-如果成功,它将获取响应(JSON数组)并请求将对象解组到Array [Profile]。 (配置文件模型并不重要)。 Unmarshall方法的结果是Future [Array [Profile]]

3-如果成功,我想将结果发送回原始发件人!

我设法做到这一点,但这是一个技巧,因为我将发件人保存在一个变量中,该变量在范围( requester )中可见。 我知道有管道模式,因此我可以在理论上将 responseAsProfiles 对象发送回发送者,但是该对象是在 responseFuture 对象的onComplete方法内创建的(当然,我们必须等待它!)

仅此而已! 在这种情况下,如何使用管道模式将结果发送回发送方? 提前谢谢!!!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)