在Vert.x最佳实践中处理数百条路线

时间:2019-10-13 10:48:15

标签: kotlin vert.x coroutine

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

1 个答案:

答案 0 :(得分:3)

您正在寻找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
}