, Spray Akka HTTP. , . Akka HTTP, Spray, HTTP- Akka Spray:
, Http.Unbind
HttpListener
(ActorRef
Http.Bound
).
Http.Unbound
( Http.CommandFailed
). .
-, SimpleRoutingApp
, startServer
. HttpListener
. , Http.Unbind
, .
, , HttpListener
:
import akka.actor._
import spray.can.Http
import spray.routing._
object MyActor {
case object GetListener
def props(route: => Route): Props = Props(new MyActor(route))
}
class MyActor(route: => Route) extends HttpServiceActor {
import MyActor._
var httpListener: Option[ActorRef] = None
def routeReceive: Receive = runRoute(route)
def serverLifecycleReceive: Receive = {
case b: Http.Bound =>
println(s"Successfully bound to ${b.localAddress}")
val listener = sender()
httpListener = Some(listener)
case GetListener =>
httpListener.foreach(sender ! _)
}
def receive = routeReceive orElse serverLifecycleReceive
}
SimpleRoutingApp
, :
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.Success
import akka.actor._
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
import spray.http._
import spray.routing._
import MyActor
object Main extends App {
implicit val system = ActorSystem()
import system.dispatcher
implicit val timeout = Timeout(5.seconds)
val route = ???
val handler = system.actorOf(MyActor.props(route), name = "handler")
IO(Http) ! Http.Bind(handler, interface = "0.0.0.0", port = 9100)
(handler ? MyActor.GetListener)
.flatMap { case actor: ActorRef => (actor ? Http.Unbind) }
.onComplete {
case Success(u: Http.Unbound) =>
println("Unbinding from the port is done.")
case _ =>
println("Unbinding failed.")
}
}
, ( ) . , , , . , , ( Spray)
object Main extends App with SimpleRoutingApp {
implicit val system = ActorSystem("simple-routing-app")
import system.dispatcher
val route = ...
~ (post | parameter('method ! "post")) {
path("stop") {
complete {
system.scheduler.scheduleOnce(1.second)(system.shutdown())(system.dispatcher)
"Shutting down in 1 second..."
}
}
}
startServer("0.0.0.0", port = 9100) {
route
}.onComplete {
case Success(b) =>
println(s"Successfully bound to ${b.localAddress}")
case Failure(ex) =>
println(ex.getMessage)
system.shutdown()
}
}