当它通过管道传递给演员

时间:2016-08-17 11:20:03

标签: scala akka akka-http

我的代码是基于Akka文档中的示例,所以它应该作为魅力,但问题是我只收到响应的标题,内容长度,当涉及折叠正文时我得到:

  

[INFO] [08/17/2016 13:01:21.116] [default-akka.actor.default-dispatcher-9] [akka:// default / user / $ a]时长:29407

     

[INFO] [08/17/2016 13:01:21.127] [default-akka.actor.default-dispatcher-9] [akka:// default / user / $ a]得到回复,正文:列表( )

演员代码:

class AkkaHttp extends Actor with ActorLogging {

  import akka.pattern.pipe
  import context.dispatcher

  final implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system))

  val http = Http(context.system)

  override def preStart() = {
    http.singleRequest(HttpRequest(uri = "http://akka.io/"))
      .pipeTo(self)
  }

  def receive = {
    case s: String => {
      log.info(s)
    }
    case HttpResponse(StatusCodes.OK, headers, entity, _) => {
      log.info("Length: " + entity.contentLengthOption.getOrElse("No content"))
      log.info("Got response, body: " + entity.dataBytes.runFold(ByteString.empty) {
        case (acc, b) => acc ++ b }.map(s => s.utf8String))
    }
    case HttpResponse(code, _, _, _) =>
      log.info("Request failed, response code: " + code)
  }

}

如果我更改preStart()方法以在其中折叠响应并仅发送String,则会记录页面主体:

  override def preStart() = {
    val httpRequest: HttpRequest = HttpRequest(uri = "http://akka.io/")
    val request = http.singleRequest(httpRequest)
    request.flatMap { response =>
      response.entity.dataBytes.runFold(ByteString.empty) { 
          case (acc, b) => acc ++ b }.map(f => f.utf8String)
    }
    .pipeTo(self)
  }

在第一个版本中,响应实体没有折叠的原因是什么?

1 个答案:

答案 0 :(得分:2)

runFold的结果是另一个Future。然后,您尝试打印Future,这不会产生任何有价值的东西,因为它是Future,而不是您想要的基础String。如果您将receive中的案例更改为此内容,则应该开始工作:

case HttpResponse(StatusCodes.OK, headers, entity, _) => 
  log.info("Length: " + entity.contentLengthOption.getOrElse("No content"))

  val entityFut = 
    entity.dataBytes.runFold(ByteString.empty) {
      case (acc, b) => acc ++ b 
    }.
    map(s => s.utf8String)
  entityFut pipeTo self