Kotlin Asynchronous Framework, Ktor 2.0, released with new plugins feature

0

After more than a year of development, Ktor 2.0, the Kotlin framework for building asynchronous client and server applications, has been released with new features and breaking changes.

On the server side, Ktor 2.0 introduces a new feature called Plugins, formerly called Features, to improve the extensibility of the framework. As its name suggests, it allows the implementation of the architecture of the plugin to extend the functionalities in a simplified way.

It also introduces Kotlin/Native support to complement the existing GraalVM support added in Ktor 1.6. Other improvements include random port support, improved testing API, type-safe routing, XML serialization, and sub-routes for plugins.

On the client side, Ktor 2.0 brings a simplified API to handle common HTTP requests; the response is now of type HttpResponse and it is possible to access the response body simply with bodyAsText

Retries are now built into the client, allowing the duration between retries to be specified. Ktor 2.0 also adds client-side content negotiation functionality, while server-side it was already implemented.

In addition to the above features, the client also includes shortcut APIs for authentication such as basic() and bearer() support functions.

In order to help with the migration from previous versions to the new 2.0 version, the Ktor team provides documentation and a migration tool included in IntelliJ IDEA which aims to solve all the problems related to breaking changes and refactored packages.

Creating a simple server with Ktor is as easy as:

fun main(args: Array) {
    embeddedServer(Netty, 8080) {
        routing {
            get("https://www.infoq.com/") {
                call.respondText("Hello, world!", ContentType.Text.Html)
            }
        }
    }.start(wait = true)
}

The above code runs an embedded web server on localhost:8080installs a routing plugin and responds with “Hello, world” when receiving an HTTP GET request on the root path.

Ktor applications can be hosted in any servlet container with Servlet 3.0+ API support, such as Tomcat, or standalone using Netty or Jetty. Ktor uses Kotlin coroutines to implement asynchronous programming with an intuitive imperative flow and all the server containers mentioned above use asynchronous I/O facilities to avoid blocking threads.

Additionally, Ktor supports Websocket protocol, monitoring with Micrometer metrics, authorization with JWT and OAuth, and a variety of template engines such as Mustache, Thymeleaf, and Velocity.

Ktor is an official JetBrains product and is developed by the JetBrains team with community contributions.

Developers can learn more about building microservices-based applications with Ktor from this InfoQ tutorial by Hadi Hariri, VP of Developer Defense at JetBrains.

Share.

Comments are closed.