Akkaプロジェクトを開発している時、環境によってはCtrl-Cで終了が出来ません。なので、Enterを押すとAkkaを終了させるようなコードを書きます。
以下は簡単なSprayプロジェクトです。Bootオブジェクトの最後2行でEnterが押された時の処理を記述しています。
import akka.actor.{Actor, ActorSystem, Props}
import akka.io.IO
import spray.can.Http
import akka.pattern.ask
import akka.util.Timeout
import spray.http.MediaTypes._
import spray.routing.HttpService
import scala.concurrent.duration._
object Boot extends App {
implicit val system = ActorSystem("on-spray-can")
val service = system.actorOf(Props[MyServiceActor], "demo-service")
implicit val timeout = Timeout(5.seconds)
IO(Http) ? Http.Bind(service, interface = "localhost", port = 8080)
// Enterを押したら終了する Docker等の場合Nullが帰る
if(io.StdIn.readLine() != null)
system.terminate()
}
class MyServiceActor extends Actor with MyService {
def actorRefFactory = context
def receive = runRoute(myRoute)
}
trait MyService extends HttpService {
val myRoute =
path("") {
get {
respondWithMediaType(`text/html`) {
complete {
<html>
<body>
<h1>Say hello to <i>spray-routing</i> on <i>spray-can</i>!</h1>
</body>
</html>
}
}
}
}
}
build.sbt
libraryDependencies ++= {
val akkaV = "2.4.8"
val sprayV = "1.3.3"
Seq(
"io.spray" %% "spray-can" % sprayV,
"io.spray" %% "spray-routing" % sprayV,
"io.spray" %% "spray-json" % "1.3.2"
)
}
Revolver.settings
fork in run := true
connectInput in run := true