【问题标题】:Transform Akka http entity byte string to Long将 Akka http 实体字节字符串转换为 Long
【发布时间】:2019-01-15 17:08:32
【问题描述】:

如何从未知长度的 Akka-HTTP 响应流中读取长度?

示例:

          val futureResponse = Http(system).singleRequest(
            HttpRequest(
              HttpMethods.POST,
              "url",
              entity = HttpEntity(ContentTypes.`application/json`, "somequery".getBytes())
            ).withHeaders(RawHeader("X-Access-Token", "access token"))
          )

          futureResponse.map {
            res =>
              res.entity.dataBytes
                .map(convertToLong) // convert to long/int
                .grouped(2) // group two elments together
                .map(getRelation)// do some transform
                .runWith(someSink) // write to sink

          }

我们如何将ByteString 转换为上述流的Long

【问题讨论】:

    标签: scala akka akka-stream akka-http


    【解决方案1】:

    编写一个接受 ByteString 并返回 Long ByteString 选项的函数 => Option[Long]

    def toLong(x: ByteString): Option[Long] = {
     try{
         Some(x.decodeString("UTF-8").toLong)
         } catch {
          case e: Exception => None 
        }
    }
    

    【讨论】:

    • 或更短:def toLong(x: ByteString): Option[Long] = Try(x.decodeString("UTF-8").toLong).toOption
    猜你喜欢
    • 2016-04-06
    • 2020-12-02
    • 2019-06-21
    • 2013-11-25
    • 2015-08-30
    • 2019-10-10
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多