请看下面的代码片段。现在假设我将有数百个像“人”这样的实体。您将如何编写这样的代码以使其干净、简洁、高效、结构良好?发送
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)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您正在寻找subrouter.
https://vertx.io/docs/vertx-web/java/#_sub_routers
从我的头顶:
override suspend fun start() {
router.mountSubrouter("/person", personRouter(vertx))
// x100 if you'd like
}
Run Code Online (Sandbox Code Playgroud)
然后在您的PersonRouter.kt:
fun personRouter(vertx: Vertx): Router {
val router = Router.router(vertx)
router.get("/:id").coroutineHandler { ctx -> person(ctx) }
// More endpoints
return router
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
643 次 |
| 最近记录: |