Reputation: 336
I am currently experimenting with app-events in ktor using Netty. However the only hook that is being called is "ApplicationStarted". What am i doing wrong here?
I set breakpoints in all of the functions, the subscriptions are being made but not all of the event-listeners are invoked. Also I tried to find some explanation in the ktor docs but that was not successful.
import io.ktor.application.*
fun Application.events(){
environment.monitor.subscribe(ApplicationStarting, ::onStarting)
environment.monitor.subscribe(ApplicationStarted, ::onStarted)
environment.monitor.subscribe(ApplicationStopping, ::onStopping)
environment.monitor.subscribe(ApplicationStopped, ::onStopped)
environment.monitor.subscribe(ApplicationStopPreparing, ::onPrepareStop)
}
private fun onStarting(app: Application){
app.log.info("Application starting")
}
private fun onStarted(app: Application){
app.log.info("Application started")
}
private fun onStopping(app: Application){
app.log.info("Application stopping")
}
private fun onStopped(app: Application){
app.log.info("Application stopped")
}
private fun onPrepareStop(env: ApplicationEnvironment){
env.log.info("Preparing App Stop")
}
"Application started" appears in the log messages but no other output.
How bad am I doing, or is this a bug?
Upvotes: 4
Views: 1645
Reputation: 336
Ok I've been looking into this and found, that the amount of invoked application-level events depend on the server you are using. The following embedded servers support the following events:
+--------+----------+---------+---------------+----------+---------+ | Engine | Starting | Started | StopPreparing | Stopping | Stopped | +--------+----------+---------+---------------+----------+---------+ | Netty | NO | YES | NO | NO | NO | | CIO | NO | YES | YES | YES | YES | | Tomcat | NO | YES | NO | NO | NO | | Jetty | NO | YES | NO | NO | NO | +--------+----------+---------+---------------+----------+---------+
Tested on Ktor version 1.1.2
So it currently seems if you want to respond to application stopping events you should use CIO as the server.
EDIT:
CIO does not support HTTPS as of now, so if needed you must stick to one of the other three. However you can use the JVM runtime shutdown hook to raise a stopped event yourself. Beware that the handlers are invoked in a different thread.
private fun onStarted(app: Application){
Runtime.getRuntime()?.addShutdownHook( Thread {
app.environment.monitor.raise(ApplicationStopped, app)
})
app.log.info("Application started")
}
Upvotes: 5