寻求简洁的代码,省去冗长,结构更好

问题描述 投票:1回答:1

请看下面的代码。现在假设我将拥有数百个像“人”这样的实体。您如何编码这样的东西以使其干净,简洁,高效,结构合理? Tx

class HttpEntryPoint : CoroutineVerticle() {

    private suspend fun person(r: RoutingContext) {
        val res = vertx.eventBus().requestAwait<String>("/person/:id", "1").body()
        r.response().end(res)
    }

    override suspend fun start() {
        val router = Router.router(vertx)
        router.get("/person/:id").coroutineHandler { ctx -> person(ctx) }
        vertx.createHttpServer()
            .requestHandler(router)
            .listenAwait(config.getInteger("http.port", 8080))
    }

    fun Route.coroutineHandler(fn: suspend (RoutingContext) -> Unit) {
        handler { ctx ->
            launch(ctx.vertx().dispatcher()) {
                try {
                    fn(ctx)
                } catch (e: Exception) {
                    e.printStackTrace()
                    ctx.fail(e)
                }
            }
        }
    }
}
kotlin vert.x coroutine
1个回答
0
投票

您正在寻找subrouter

https://vertx.io/docs/vertx-web/java/#_sub_routers

从我的头顶:

override suspend fun start() {
    router.mountSubrouter("/person", personRouter(vertx)) 
    // x100 if you'd like
}

然后输入PersonRouter.kt

fun personRouter(vertx: Vertx): Router {
    val router = Router.router(vertx)
    router.get("/:id").coroutineHandler { ctx -> person(ctx) }
    // More endpoints
    return router
}
© www.soinside.com 2019 - 2024. All rights reserved.