LoginSignup
3
3

More than 5 years have passed since last update.

ScalaのAkkaで実行途中で終了する

Last updated at Posted at 2016-08-02

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
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3