简体   繁体   English

为什么akka http不对前N个请求发出响应?

[英]Why akka http is not emiting responses for first N requests?

I'm trying to use akka-http in order to make http requests to a single host (eg "akka.io"). 我试图使用akka-http来向单个主机发出http请求(例如“ akka.io”)。 The problem is that the created flow (Http().cachedHostConnectionPool) starts emitting responses only after N http requests are made, where N is equal to max-connections. 问题在于创建的流(Http()。cachedHostConnectionPool)仅在发出N个http请求后才开始发出响应,其中N等于最大连接数。

import scala.util.Failure
import scala.util.Success
import com.typesafe.config.ConfigFactory
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.Uri.apply
import akka.http.scaladsl.settings.ConnectionPoolSettings
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Sink
import akka.stream.scaladsl.Source

object ConnectionPoolExample extends App {

  implicit val system = ActorSystem()
  implicit val executor = system.dispatcher
  implicit val materializer = ActorMaterializer()

  val config = ConfigFactory.load()

  val connectionPoolSettings = ConnectionPoolSettings(config).withMaxConnections(10)
  lazy val poolClientFlow = Http().cachedHostConnectionPool[Unit]("akka.io", 80, connectionPoolSettings)

  val fakeSource = Source.fromIterator[Unit] { () => Iterator.continually { Thread.sleep(1000); () } }
  val requests = fakeSource.map { _ => println("Creating request"); HttpRequest(uri = "/") -> (()) }

  val responses = requests.via(poolClientFlow)

  responses.runForeach {
    case (tryResponse, jsonData) =>
      tryResponse match {
        case Success(httpResponse) =>
          httpResponse.entity.dataBytes.runWith(Sink.ignore)
          println(s"status: ${httpResponse.status}")
        case Failure(e) => {
          println(e)
        }
      }
  }
}

The output looks like this: 输出看起来像这样:

Creating request
Creating request
Creating request
Creating request
Creating request
Creating request
Creating request
Creating request
Creating request
Creating request
status: 200 OK
Creating request
status: 200 OK
Creating request
status: 200 OK
...

I am failing to find any configuration parameters which would allow emitting responses as soon as they are ready and not when the pool is out of free connections. 我找不到任何配置参数,这些参数将允许它们在准备就绪时发出响应,而不是在池没有可用连接时发出响应。

Thanks! 谢谢!

The reason is that you block the client from doing other work by calling Thread.sleep —that method is simply forbidden inside reactive programs. 原因是您通过调用Thread.sleep阻止了客户端执行其他工作-该方法在反应式程序中只是被禁止。 The proper and simpler approach is to use Source.tick . 正确而简单的方法是使用Source.tick

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM