gpt4 book ai didi

scala - 我如何计算 akka 当前打开的连接

转载 作者:行者123 更新时间:2023-12-04 16:07:04 25 4
gpt4 key购买 nike

我正在研究 akka http

  "com.typesafe.akka" %% "akka-actor" % "2.4.6",
"com.typesafe.akka" % "akka-http-experimental_2.11" % "2.4.6"

我正在测试简单的代码,如下所示。
我的主要问题是如何增强它以获得关闭连接的通知,以便我可以打印当前打开的连接数?
object StatsRepo{
val totConn = new AtomicInteger(0)
val currOpenConn = new AtomicInteger(0) // how to count this?
}

object Boot2 extends App{
implicit val system = ActorSystem("akka-http")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher

val requestHandler: HttpRequest => Future[HttpResponse] = {
// do some work here...
}
val serverSource = Http().bind("0.0.0.0", 8080)


val bindingFuture: Future[Http.ServerBinding] =
serverSource.to(Sink.foreach { connection =>
StatsRepo.totConn.incrementAndGet()
connection handleWithAsyncHandler requestHandler
}).run()
println(s"Server online at http://0.0.0.0:9090")
}

最佳答案

像这样的事情可能会奏效:

val bindingFuture: Future[Http.ServerBinding] =
serverSource.to(Sink.foreach { connection =>
StatsRepo.totConn.incrementAndGet()
connection.handleWith(
Flow[HttpRequest].mapAsync(1)(requestHandler)
.watchTermination()((_, connClosedFuture) => {
connClosedFuture.onComplete(_ => currOpenConn.decrementAndGet())
}))
}).run()

watchTermination

关于scala - 我如何计算 akka 当前打开的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37394447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com