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

Kotlin 在Vert.x最佳实践中处理数百条路线,kotlin,vert.x,coroutine,Kotlin,Vert.x,Coroutine,请看下面的代码。现在假设我有数百个实体,比如“person”。您将如何编写这样的代码以使其干净、简洁、高效、结构良好?德克萨斯州 class HttpEntryPoint : CoroutineVerticle() { private suspend fun person(r: RoutingContext) { val res = vertx.eventBus().requestAwait<String>("/person/:id", "1").body(

请看下面的代码。现在假设我有数百个实体,比如“person”。您将如何编写这样的代码以使其干净、简洁、高效、结构良好?德克萨斯州

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)
                }
            }
        }
    }
}
class-HttpEntryPoint:CoroutineVerticle(){
私人娱乐人(r:RoutingContext){
val res=vertx.eventBus().requestAwait(“/person/:id”,“1”).body()
r、 响应().end(res)
}
覆盖暂停乐趣开始(){
val路由器=路由器。路由器(vertx)
router.get(“/person/:id”).coroutineHandler{ctx->person(ctx)}
vertx.createHttpServer()
.requestHandler(路由器)
.listenAwait(config.getInteger(“http.port”,8080))
}
有趣的路线.coroutineHandler(fn:suspend(RoutingContext)->Unit){
处理程序{ctx->
启动(ctx.vertx().dispatcher()){
试一试{
fn(ctx)
}捕获(e:例外){
e、 printStackTrace()
ctx.故障(e)
}
}
}
}
}

您正在寻找
子计算机

从我的头顶:

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
}

您正在寻找
子计算机

从我的头顶:

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
}

你能澄清一下你到底关心什么吗?您是否担心在添加了更多端点后会有一个非常大的、可能无法管理的类?我们的朋友,你还担心什么吗?嗨,皮洛克。是的,我担心有不可管理的类一旦我添加了数百个端点在
start
中,您可以将路由器对象传递给另一个类/函数。这样,您就可以拥有单独的类,每个类负责单独的端点组,然后您当前的类将只包含引用,以明确您所关心的是什么?您是否担心在添加了更多端点后会有一个非常大的、可能无法管理的类?我们的朋友,你还担心什么吗?嗨,皮洛克。是的,我担心有不可管理的类一旦我添加了数百个端点在
start
中,您可以将路由器对象传递给另一个类/函数。这样,您可以有单独的类,每个类负责单独的端点组,然后您当前的类将只保存对的引用