Handling hundreds of routes in Vert.x best practices

我是研究僧i 提交于 2021-01-28 08:43:32

问题


Please have a look at the piece of code below. Now suppose i'll have hundreds of entity like "person". How would you code such a thing to get it clean, concise, efficient, well structured ? 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:


You're looking for subrouter.

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

From the top of my head:

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

Then in your PersonRouter.kt:

fun personRouter(vertx: Vertx): Router {
    val router = Router.router(vertx)
    router.get("/:id").coroutineHandler { ctx -> person(ctx) }
    // More endpoints
    return router
}


来源:https://stackoverflow.com/questions/58362832/handling-hundreds-of-routes-in-vert-x-best-practices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!