使用喷涂示例进行分块响应处理

时间:2013-05-02 10:07:25

标签: http scala spray

文档states,喷雾能够处理分块响应,但我找不到任何开始的例子。有我天真的实施:

object Main extends App {

  implicit val system = ActorSystem()
  import system.dispatcher
  val log = Logging(system, getClass)
  val ioBridge = IOExtension(system).ioBridge()
  val httpClient = system.actorOf(Props(new HttpClient(ioBridge)))

  val conduit = system.actorOf(
    props = Props(new HttpConduit(httpClient, "localhost", 3000)),
    name = "http-conduit"
  )

  val pipeline = HttpConduit.sendReceive(conduit)
  val response = pipeline(
    HttpRequest(
      method = GET,
      uri = "/output.cgi.xml"
    )
  )

  response onComplete {
    case Success(a) =>
      log.info("Success: " + a)
      system.shutdown()

    case Failure(error) =>
      log.error(error, "Failure")
      system.shutdown()
  }

}

我已设置response-chunk-aggregation-limit = 0,但仍然没有发生任何事情。

您能为我提供阅读分块响应的示例吗?

更新

我已将代码改写如下:

object Main extends App {

  implicit val system = ActorSystem()
  import system.dispatcher
  val log = Logging(system, getClass)
  val ioBridge = IOExtension(system).ioBridge()
  val httpClient = system.actorOf(Props(new HttpClient(ioBridge)))

  actor(new Act {
    httpClient ! Connect(new InetSocketAddress("localhost", 3000))

    become {
      case Connected(_) =>
        log.info("connected")
        sender ! HttpRequest(GET, "/output.cgi.xml")
      case Closed(handle, reason) =>
        log.info("closed: " + reason)
        system.shutdown()
      case ChunkedResponseStart(res) =>
        log.info("start: " + res)
      case MessageChunk(body, ext) =>
        log.info("chunk: " + body)
      case ChunkedMessageEnd(ext, trailer) =>
        log.info("end: " + ext)
      case m =>
        log.info("received unknown message " + m)
        system.shutdown()
    }
  })

}

现在我在建立连接后就收到了closed: ProtocolError(Aggregated response entity greater than configured limit of 1048576 bytes)

我的application.conf

spray.can {
  client {
    response-chunk-aggregation-limit = 0
  }
}

1 个答案:

答案 0 :(得分:9)

正如您所注意到的,HttpConduit仅适用于聚合响应。你必须摔倒到喷雾罐层才能处理单个块。

不幸的是,我们目前没有示例显示您将如何执行此操作。粗略地说,它的工作原理如下(在M7中):

  1. 设置response-chunk-aggregation-limit = 0
  2. Connect发送给httpClient actor并等待Connected
  3. HttpRequest发送给Connected消息的发件人
  4. 处理分块请求消息ChunkedResponseStartMessageChunkChunkedResponseEnd
  5. 有关详细信息,请参阅http://spray.io/documentation/spray-can/http-client/#chunked-responses

    与使用HttpConduit相比,这意味着您必须自己管理您的连接(如果这就是您使用HttpConduit的原因)。在最近的夜晚,它变得更容易,因为新的HttpClient自动支持连接池等。如果您需要,您还可以在邮件列表中获得更多信息。