如何使用基于请求参数的Flows在akka-http中引入非阻塞延迟

时间:2018-03-01 16:33:29

标签: scala akka akka-stream akka-http

我正在启动服务器并使用akka stream

处理它
connection.handleWith(handleRequest())

其中handleRequest():Flow[HttpRequest,HttpRespnse,_] 我需要根据查询参数创建一个将响应发送回客户端的延迟。我可以提取查询参数,我无法弄清楚,如何使用此创建延迟。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

扩展@KnowsNotMuch答案,假设您有一些标准可以决定是否延迟请求:

val shouldDelayRequest : (HttpRequest) => Boolean = ???

您可以使用此决策程序创建DelayStrategy

import scala.concurrent.duration.{FiniteDuration, TimeUnit}

val noDelay : FiniteDuration = FiniteDuration(0L, TimeUnit.SECONDS)

val createDelayStrategy : (FiniteDuration) => () => DelayStrategy[HttpRequest] = 
  (finiteDelay) => () => new DelayStrategy[HttpRequest] {
    override def nextDelay(elem: HttpRequest) : FiniteDuration = 
      if(shouldDelayRequest(elem))
        finiteDelay
      else
        noDelay
  }

您可以使用此功能创建DelayFlow

import akka.stream.contrib.DelayFlow

val delay = FiniteDuration(42L, TimeUnit.Seconds)

val delayFlow : DelayFlow[HttpRequest] = DelayFlow(createDelayStrategy(delay))

然后,可以将此delayFlow连接到您将请求处理到响应中的任何功能:

val requestToResponseFlow : Flow[HttpRequest, HttpResponse, _] = ???

val possibleDelayedResponseFlow  : Flow[HttpRequest, HttpResponse, _] = 
  delayFlow via requestToResponseFlow