KotlinのフレームワークKtorについて調べた
Ktorは、JetBrains社が開発しているKotlinで書かれた軽量なフレームワーク
Kotlinの特徴を最大限に活かしながら、柔軟かつ簡潔な非同期処理を提供するフレームワークで、特に非同期処理や並行処理を容易に行うことができる
Ktorを使えば、簡単にHTTPサーバーやクライアントアプリケーションを構築でき、RESTful APIやWebSocket、認証などの機能もサポートされている
1. Ktorの特徴
- Kotlinファースト: KtorはKotlin専用に設計されており、Kotlinのすべての機能(コルーチンやDSLなど)を活用できる
- 非同期処理: Kotlinのコルーチンをネイティブにサポートしており、非同期処理が簡単に実装できる
- 軽量でシンプル: 必要な機能をプラグインとして柔軟に追加できるため、シンプルかつ軽量なアプリケーション開発が可能
- 多目的: サーバーサイド(REST API、WebSocketなど)だけでなく、クライアントサイド(HTTPクライアント)でも利用可能
- クロスプラットフォーム: KtorはJVM、Android、iOS、JavaScript、Nativeなど多くのプラットフォームで動作する
2. Ktorの基本構造
Ktorは、サーバーアプリケーションとクライアントアプリケーションの両方に対応している
1. Ktorサーバーの基本構造
Ktorサーバーアプリケーションは、主に以下の構成要素から成り立っています。
- ルーティング(Routing): 各エンドポイント(URLパス)とハンドラーを定義する
- プラグイン: 認証、セッション管理、リクエスト解析、レスポンスフォーマット(JSONなど)などの機能を追加する拡張可能なモジュール
- コルーチン: 非同期処理をサポートするために使用される
3. Ktorサーバーアプリケーションの作成
手っ取り早くKtorサーバーアプリケーションを作成するため、以下のページからsampleをダウンロードする
ダウンロードしたら解凍してビルドして実行する
myprojects> cd ktor-sample-app ktor-sample-app> ./gradlew build ktor-sample-app> ./gradlew run
これで画面にHello Worldが出ればOK
build.gradle.ktsの中を見るとKtorの依存関係を追加されている
val kotlin_version: String by project val logback_version: String by project plugins { kotlin("jvm") version "2.0.20" id("io.ktor.plugin") version "3.0.0-rc-1" } group = "com.example" version = "0.0.1" application { mainClass.set("io.ktor.server.netty.EngineMain") val isDevelopment: Boolean = project.ext.has("development") applicationDefaultJvmArgs = listOf("-Dio.ktor.development=$isDevelopment") } repositories { mavenCentral() } dependencies { implementation("io.ktor:ktor-server-core-jvm") implementation("io.ktor:ktor-server-netty-jvm") implementation("ch.qos.logback:logback-classic:$logback_version") implementation("io.ktor:ktor-server-config-yaml") testImplementation("io.ktor:ktor-server-test-host-jvm") testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version") }
サーバーサイドの実装は、サンプルコードでは、Application.ktと/plugins/Routing.ktの2つのファイルが作られていて、それぞれ以下のようになっている
package com.example import com.example.plugins.* import io.ktor.server.application.* fun main(args: Array<String>) { io.ktor.server.netty.EngineMain.main(args) } fun Application.module() { configureRouting() }
package com.example.plugins import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.configureRouting() { routing { get("/") { call.respondText("Hello World!") } } }
ルーティングは/plugins/Routing.ktで設定され、エンドポイント(/)を定義している
call.respondTextでテキストを返している
とりあえず動かすところまではすぐ作れたので、これから色々プラグインを足して試していきたい