Skip to content

Native 服务器 ​

Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。目前,在 Kotlin/Native 下运行 Ktor 服务器存在以下限制:

在 Kotlin/Native 项目中使用 Ktor 需要使用新的内存管理器,从 Kotlin 1.7.20 开始默认启用。

添加依赖项 ​

Kotlin/Native 项目中的 Ktor 服务器至少需要两个依赖项:

  • ktor-server-core(核心依赖项)
  • ktor-server-cio(CIO 引擎)

以下示例在 build.gradle.kts 文件中的 nativeMain 源集中添加依赖项:

kotlin
kotlin {
    sourceSets {
        nativeMain.dependencies {
            implementation(ktorLibs.server.core)
            implementation(ktorLibs.server.cio)
        }
    }
}
上述代码段使用 Ktor version catalog 来指定 Ktor 依赖项。

要测试 Native 服务器,请将 ktor-server-test-host 构件添加到 nativeTest 源集中:

kotlin
kotlin {
    sourceSets {
        nativeTest.dependencies {
            implementation(libs.kotlin.test)
            implementation(ktorLibs.server.testHost)
        }
    }
}

配置原生目标 ​

指定所需的原生目标并使用 binaries 属性声明原生二进制文件:

kotlin
kotlin {
    val hostOs = System.getProperty("os.name")
    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")
        // Other supported targets are listed here: 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 服务器。