【问题标题】:Scala read continuous http streamScala读取连续的http流
【发布时间】:2016-01-11 10:49:08
【问题描述】:

如何在 scala 中连接并读取连续(分块)的 http 流?例如,如果我有这个用 python/bottle 编写的简单服务:

from gevent import monkey; monkey.patch_all()

import gevent
from bottle import route, run

@route('/stream')
def stream():
    while True:
        yield 'blah\n'
        gevent.sleep(1)

run(host='0.0.0.0', port=8100, server='gevent')

我打算使用akka-stream 来处理数据,我只需要一种方法来检索它。

【问题讨论】:

    标签: python scala bottle http-streaming akka-stream


    【解决方案1】:

    这应该可行。基本上,您对产生分块响应的 uri 执行单个请求。响应实体包含一个 dataBytes 流。在分块响应的情况下,这将是块流。如果是非分块响应 (HttpEntity.Strict),这将是一个只有一个块的流。

    显然您也可以在实体上显式匹配以查看它是否为 HttpEntity.Chunked,但通常您也希望保留处理非分块响应的能力。

    在现实世界的应用程序中,您不会使用 runForeach 来执行副作用,而是使用 dataBytes 流进行一些处理。

    import akka.actor.ActorSystem
    import akka.http.scaladsl.Http
    import akka.http.scaladsl.model.{Uri, HttpRequest}
    import akka.stream.ActorMaterializer
    
    object ChunkTestClient extends App {
    
      implicit val system = ActorSystem("test")
      import system.dispatcher
    
      implicit val materializer = ActorMaterializer()
      val source = Uri("https://jigsaw.w3.org/HTTP/ChunkedScript")
      val finished = Http().singleRequest(HttpRequest(uri = source)).flatMap { response =>
        response.entity.dataBytes.runForeach { chunk =>
          println(chunk.utf8String)
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 2021-11-13
      • 2011-11-19
      • 2015-02-05
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多