原生伺服器
程式碼範例: embedded-server-native
Ktor 支援 Kotlin/Native,並允許您在沒有額外執行階段或虛擬機的情況下執行伺服器。目前,在 Kotlin/Native 下執行 Ktor 伺服器有以下限制:
undefined
新增相依性
在 Kotlin/Native 專案中,Ktor 伺服器至少需要兩個相依性:ktor-server-core 相依性以及引擎相依性 (CIO)。下方的程式碼片段顯示如何將相依性新增至 build.gradle.kts 檔案中的 nativeMain 原始碼集:
kotlin
}
sourceSets {
val nativeMain by getting {
dependencies {
implementation("io.ktor:ktor-server-core:$ktor_version")
implementation("io.ktor:ktor-server-cio:$ktor_version")
}
}若要測試原生伺服器,請將 ktor-server-test-host 構件新增至 nativeTest 原始碼集:
kotlin
}
}
val nativeTest by getting {
dependencies {
implementation(kotlin("test"))
implementation("io.ktor:ktor-server-test-host:$ktor_version")
}
}設定原生目標
指定所需的原生目標,並使用 binaries 屬性宣告原生二進位檔:
kotlin
val arch = System.getProperty("os.arch")
val nativeTarget = when {
hostOs == "Mac OS X" && arch == "x86_64" -> macosX64("native")
hostOs == "Mac OS X" && arch == "aarch64" -> macosArm64("native")
hostOs == "Linux" && (arch == "x86_64" || arch == "amd64") -> linuxX64("native")
hostOs == "Linux" && arch == "aarch64" -> linuxArm64("native")
hostOs.startsWith("Windows") -> mingwX64("native")
// 其他支援的目標列於此處:https://ktor.io/docs/server-native.html#targets
else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
}
nativeTarget.apply {
binaries {
executable {
entryPoint = "main"
}
}您可以在此處找到完整的範例:embedded-server-native。
建立伺服器
設定完 Gradle 建置指令碼後,您可以按照此處的說明建立 Ktor 伺服器:建立伺服器。
