Scala spray - init on server statup

229 views Asked by At

I would like to load some data from JSON files when spray server starts-up, How can it be done? How can I write code when server loads like "init" method of Servlets?

3

There are 3 answers

1
mingchuno On BEST ANSWER

Try this:

object Boot extends App {
    val jsonData: Option[String] = laodJsonFromFile()
    val service = system.actorOf(Props(classOf[YourServiceActor], jsonData), "YourServiceActor")
    implicit val timeout = Timeout(5.seconds)
    // start a new HTTP server on port 80 with our service actor as the handler
    IO(Http) ? Http.Bind(service, 0.0.0.0, 80)

    private def laodJsonFromFile() = // some code...
}

class YourServiceActor(jsonData: Option[String]) extends Actor {
    // ... your code
}
0
suztomo On

Use "object" and initialize needful when it's created at application initialization.

0
Soumya Simanta On

How are you starting your Spray server?

Assuming you a main or App that starts your server, you can just write the JSON loading code before you load your Spray routes.