6

I'm looking into akka http

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

I'm testing the simple code, as below. My main question is how is it possible to enhance it to get also notification for closed connection, So I can print the number of currently opened connections?

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")
}
Julias
  • 5,752
  • 17
  • 59
  • 84

1 Answers1

1

Something like this might work:

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()

See watchTermination

Rich
  • 15,048
  • 2
  • 66
  • 119