Ktor Basics

Ktor is a Kotlin based asynchronous web framework.

Backends need to be versatile and scalable. Developers should have a 'microservice mindset' to create more maintainable backend services.

Why Ktor

What is a Servlet Container?

Which to Choose?

Tomcat

Jetty

Netty

CIO

For Ktor the buzzword is asynchronous, and I plan on experimenting with socket programming, so my choice is Netty.

Note: I think there is also support for Apache and Android as a buit in http client engine but the documentation doesn't go into great detail

Starting a Project

Either go to start.ktor.io or use the Intellij plugin to generate a project template. Select whatever add-ons you want but always make sure 'routing' is selected

Other add-ons I would concider basic:

The Kotlin Coroutine

The Kotin corourine is an asynchronous non-blocking job that can run on the same thread as other coroutines.

Installation and Configuration of Features

    install(CallLogging) {
        level = Level.INFO
        filter { call -> call.request.path().startsWith("/") }
    }
	install(Routing) {
		get("/") {
			call.respondText("Good evening World")
		}
	}

Common Features

install(Routing) {
	get("/") {
		call.respondText("Good evening World")
	}
}

can be seperated into install(Routing) and

routing {
	get("/") {
		call.respondText("Good evening World")
	}
}

Although, this is a bad example, because Routing is installed by default so there's no need for install(Routing)

Custom Features

You can build and install your own custom features. Most features intercept the pipeline at the Application.Features phase. That's all I'm going to say about that.

Autoreload

Gradle: Recompile

Call Logging - Log All Incoming Requests

install(CallLogging) {
	level = Level.INFO
	filter { call -> call.request.path().startsWith("/mysection1") } 
}

Metrics Statistics on the Usage of Endpoints

    implementation("io.ktor:ktor-metrics:$ktor_version")
    implementation("io.dropwizard.metrics:metrics-jmx:4.0.0")

Then install the feature:

    install(DropwizardMetrics) {
        Slf4jReporter.forRegistry(registry)
            .outputTo(log)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build()
            .start(15, TimeUnit.SECONDS)

        JmxReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build()
            .start()
    }


Revision #1
Created 16 April 2022 23:57:49 by Elkip
Updated 17 April 2022 01:02:09 by Elkip