Skip to content

程式碼中的配置

Ktor 允許您直接在程式碼中配置各種伺服器參數,包括主機位址、port、伺服器模組模組可讓您透過對路由進行分組來建構應用程式。等等。配置方式取決於您設定伺服器的方式 —— 使用 embeddedServer 或 EngineMain了解如何根據您的應用程式部署需求建立伺服器。。

使用 embeddedServer 時,您可以透過將所需的參數直接傳遞給該函式來配置伺服器。 embeddedServer 函式接受用於配置伺服器的不同參數,包括 伺服器引擎了解處理網路請求的引擎。、伺服器監聽的主機與 port,以及其他配置。

在本節中,我們將查看幾個執行 embeddedServer 的不同範例,說明如何配置伺服器以發揮其優勢。

基本配置

下方的程式碼片段顯示了使用 Netty 引擎與 8080 port 的基本伺服器設定。

kotlin
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main(args: Array<String>) {
    embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                call.respondText("Hello, world!")
            }
        }
    }.start(wait = true)
}

請注意,您可以將 port 參數設定為 0 以在隨機 port 上執行伺服器。 embeddedServer 函式會回傳一個引擎執行個體,因此您可以使用 ApplicationEngine.resolvedConnectors 函式在程式碼中獲取 port 值。

引擎配置

embeddedServer 函式允許您使用 configure 參數傳遞特定於引擎的選項。此參數包含所有引擎通用的選項,並由 ApplicationEngine.Configuration 類別公開。

下方的範例顯示如何使用 Netty 引擎配置伺服器。在 configure 區塊內,我們定義了一個 connector 來指定主機與 port,並自訂各種伺服器參數:

kotlin
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main(args: Array<String>) {
    embeddedServer(Netty, configure = {
        connectors.add(EngineConnectorBuilder().apply {
            host = "127.0.0.1"
            port = 8080
        })
        connectionGroupSize = 2
        workerGroupSize = 5
        callGroupSize = 10
        shutdownGracePeriod = 2000
        shutdownTimeout = 3000
    }) {
        routing {
            get("/") {
                call.respondText("Hello, world!")
            }
        }
    }.start(wait = true)
}

connectors.add() 方法定義了一個具有指定主機 (127.0.0.1) 與 port (8080) 的連接器。

除了這些選項之外,您還可以配置其他特定於引擎的屬性。

Netty

特定於 Netty 的選項由 NettyApplicationEngine.Configuration 類別公開。

kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main() {
    embeddedServer(Netty, configure = {
        requestQueueLimit = 16
        shareWorkGroup = false
        configureBootstrap = {
            // ...
        }
        responseWriteTimeoutSeconds = 10
    }) {
        // ...
    }.start(true)
}

Jetty

特定於 Jetty 的選項由 JettyApplicationEngineBase.Configuration 類別公開。

您可以在 configureServer 區塊內配置 Jetty 伺服器,該區塊提供了對 Server 執行個體的存取。

使用 idleTimeout 屬性指定連線在關閉前可以保持閒置的時間長度。

kotlin
import io.ktor.server.engine.*
import io.ktor.server.jetty.jakarta.*

fun main() {
    embeddedServer(Jetty, configure = {
        configureServer = { // this: Server -&gt;
            // ...
        }
        idleTimeout = 30.seconds
    }) {
        // ...
    }.start(true)
}

CIO

特定於 CIO 的選項由 CIOApplicationEngine.Configuration 類別公開。

kotlin
import io.ktor.server.engine.*
import io.ktor.server.cio.*

fun main() {
    embeddedServer(CIO, configure = {
        connectionIdleTimeoutSeconds = 45
    }) {
        // ...
    }.start(true)
}

Tomcat

如果您使用 Tomcat 作為引擎,可以使用 configureTomcat 屬性進行配置,該屬性提供了對 Tomcat 執行個體的存取。

kotlin
import io.ktor.server.engine.*
import io.ktor.server.tomcat.jakarta.*

fun main() {
    embeddedServer(Tomcat, configure = {
        configureTomcat = { // this: Tomcat -&gt;
            // ...
        }
    }) {
        // ...
    }.start(true)
}

自訂環境

下方的範例顯示如何使用 ApplicationEngine.Configuration 類別代表的自訂配置,執行具有多個連接器端點的伺服器。

kotlin
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main() {
    val appProperties = serverConfig {
        module { module() }
    }
    embeddedServer(Netty, appProperties) {
        envConfig()
    }.start(true)
}

fun ApplicationEngine.Configuration.envConfig() {
    connector {
        host = "0.0.0.0"
        port = 8080
    }
    connector {
        host = "127.0.0.1"
        port = 9090
    }
}

如需完整範例,請參閱 embedded-server-multiple-connectors 。

您也可以使用自訂環境來 提供 HTTPS 服務 。

命令列配置

Ktor 允許您使用命令列引數動態地配置 embeddedServer。這在需要在執行階段指定 port、主機或逾時等配置的情況下特別有用。

為此,請使用 CommandLineConfig 類別將命令列引數解析為配置物件,並將其傳遞至配置區塊中:

kotlin
fun main(args: Array<String>) {
    embeddedServer(
        factory = Netty,
        configure = {
            val cliConfig = CommandLineConfig(args)
            takeFrom(cliConfig.engineConfig)
            loadCommonConfiguration(cliConfig.rootConfig.environment.config)
        }
    ) {
        routing {
            get("/") {
                call.respondText("Hello, world!")
            }
        }
    }.start(wait = true)
}

在此範例中,來自 Application.Configuration 的 takeFrom() 函式用於覆蓋引擎配置值,例如 port 和 host。 loadCommonConfiguration() 函式則從根環境載入配置,例如逾時。

要執行伺服器,請按以下方式指定引數:

shell
./gradlew run --args="-port=8080"
對於靜態配置,您可以使用設定檔或環境變數。 若要了解更多,請參閱 檔案中的配置 。