2016-05-23 16 views
5

sto cercando in Akka httpcome posso contare Akka attuali connessioni aperte

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

sto testando il codice semplice, come di seguito. La mia domanda principale è come è possibile migliorarla per ottenere anche la notifica per la connessione chiusa, quindi posso stampare il numero di connessioni attualmente aperte?

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") 
} 

risposta

0

Qualcosa di simile potrebbe funzionare:

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

Vedi watchTermination

Problemi correlati