【问题标题】:Several sites on one instance of the Ktor serverKtor 服务器的一个实例上的多个站点
【发布时间】:2021-03-16 04:43:19
【问题描述】:

我希望一个 Ktor 应用程序服务于多个站点。 (一个站点=一个域) 我还希望能够在不重新启动 Ktor 服务器的情况下添加和删除站点。(这是我无法解决的主要问题)

我在文档中找到了这样的功能,但我不明白我是否可以动态添加新端口?

如果您有任何想法可以解决我的问题,请告诉我?

【问题讨论】:

    标签: kotlin server ktor


    【解决方案1】:

    connector 只是一个函数,因此您可以根据需要多次调用它:

    val APPS = mapOf(
        8080 to "Hello from 8080",
        9090 to "Hola desde 9090"
    )
    
    fun main() {
        val env = applicationEngineEnvironment {
            module {
                main()
            }
            APPS.forEach {
                connector {
                    host = "127.0.0.1"
                    port = it.key
                }
            }
        }
        embeddedServer(Netty, env).start(true)
    }
    
    fun Application.main() {
        routing {
            get("/") {
                val port = call.request.local.port
                call.respondText(APPS[port] ?: "Who are you?", ContentType.Text.Plain)
            }
        }
    }
    

    ➜  ~ curl localhost:8080
    Hello from 8080
    ➜  ~ curl localhost:9090
    Hola desde 9090
    

    但如果您只打算提供 HTTP 请求,那么由主机识别并在同一端口上运行应用程序可能是个好主意:

    val APPS = mapOf(
        "first-client.app.local:8080" to "Hello dear first client",
        "second-client.app.local:8080" to "Hola amigo"
    )
    
    fun main() {
        val server = embeddedServer(Netty, port = 8080) {
            routing {
                get("/") {
                    val host = call.request.headers["HOST"]
                    call.respondText(APPS[host] ?: "Who are you?", ContentType.Text.Plain)
                }
            }
        }
        server.start(wait = true)
    }
    

    要在本地测试,您需要将这些行添加到/etc/hosts

    127.0.0.1   first-client.app.local
    127.0.0.1   second-client.app.local
    

    然后

    ➜  ~ curl http://first-client.app.local:8080/
    Hello dear first client
    ➜  ~ curl http://second-client.app.local:8080/
    Hola amigo
    ➜  ~ curl http://localhost:8080/
    Who are you?
    

    【讨论】:

    • 谢谢,这正是我想要的!这似乎很容易,为什么我自己想不通:)
    猜你喜欢
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多