Hello again, :wave::skin-tone-4: I was doing a bi...
# ktor
h
Hello again, 👋🏽 I was doing a bit of research regarding the best approach to Gracefully Shutdown a Ktor server (Netty Engine - more specifically). Looking through the documentation, I thought that the recommended way would be through Application Monitoring Events (e.g getting SIGTERM signals). However, during my tests, I noticed that
onStopping, onPrepareStop and onStopped
ApplicationEvents are not triggered for Netty Engine? Is that expected? If so, do you have any suggestion to properly handle those Graceful Shutdowns? Thanks once again for your help.
a
I cannot reproduce your problem:
Copy code
val server = embeddedServer(Netty, port = 3333) {
   environment.monitor.subscribe(ApplicationStopping) {
       println("Stopping")
   }

    environment.monitor.subscribe(ApplicationStopped) {
        println("Stopped")
    }

    environment.monitor.subscribe(ApplicationStopPreparing) {
        println("Preparing")
    }
}

server.start(wait = false)
server.stop()
h
Did you try terminating the application with
kill -15 PID
? I'm afraid it won't print
This is how I was testing.
Copy code
fun main() {
    startKoin { modules(httpClientModule, serviceModule, useCaseModule, redisModule) }
    embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}

fun Application.module() {
    environment.monitor.subscribe(ApplicationStarting) { print("Starting") }
    environment.monitor.subscribe(ApplicationStarted) { print("Started") }
    environment.monitor.subscribe(ApplicationStopping) { print("Stopping") }
    environment.monitor.subscribe(ApplicationStopped)  { print("Stopped") }
    environment.monitor.subscribe(ApplicationStopPreparing)  { print("Preparing") }
}
Even the SIGINT signal sent by IntelliJ is not caught.
a
I believe you will have to add a shutdown hook in which you stop the server
Copy code
val server = embeddedServer(Netty, port = 8080) {
  ...
}
Runtime.getRuntime().addShutdownHook(
    thread(start = false) {
        server.stop()
    }
)
server.start(wait = true)
a
Or you can use the
addShutdownHook
method:
Copy code
server.addShutdownHook {
    server.stop()
}
h
Ohhh, I see! This is what I was missing I guess. Thanks for your help guys. 😃