0

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?

bashan
  • 3,572
  • 6
  • 41
  • 58

3 Answers3

2

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
}
mingchuno
  • 577
  • 1
  • 3
  • 10
  • Is there something to promise me that the data will be loaded before the server start answering requests? – bashan Dec 13 '14 at 18:29
1

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

suztomo
  • 5,114
  • 2
  • 20
  • 21
1

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.

Soumya Simanta
  • 11,523
  • 24
  • 106
  • 161