在Vert.x最佳实践中处理数百条路线 [英] Handling hundreds of routes in Vert.x best practices

查看:106
本文介绍了在Vert.x最佳实践中处理数百条路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)
                }
            }
        }
    }
}

推荐答案

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

这篇关于在Vert.x最佳实践中处理数百条路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆