I have a config file servers.conf
in my conf/
directory that is read by my ServerController whenever the route /servers
is hit. This isn't performant because it requires a re-read of the configuration file on each successive hit when the file won't change. Further if there are problems with the config file, I can tell the user ASAP rather than throw an exception on a page hit.
Currently I have this in my ServerController.scala
:
case class Server(ip: String, port: String)
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's server page.
*/
@Singleton
class ServerController @Inject() extends Controller {
/**
* Create an Action to render an HTML page with a the list of servers.
* The configuration in the `routes` file means that this method
* will be called when the application receives a `GET` request with
* a path of `/servers`.
*/
def index = Action {
val serverList = ConfigFactory.load().getConfigList("servers")
val servers: List[Server] = serverList match {
case null => Nil
case _ => serverList map { s =>
Server(s.getString("ip"), s.getString("port"))
} filter { s =>
s.ip != null && s.port != null
}.toList
}
Ok(views.html.servers(servers))
}
}
My goal is to have the server read the config file at startup and pass the list of servers to the ServerController when the route is hit if there are no problems reading in the config file. If there are problems, I want an exception to be thrown immediately.
I can't seem to find an entry point for my application, though, so I don't know how to perform actions on startup.
Does anyone know how to do this? I'm using Play 2.5.x.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…