如何在router.route(“/api/*”)处理程序中使用协同路由?

hkmswyz6  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(309)

我尝试在路由处理程序lambda中使用coroutine,如下所示:

private suspend fun createRoutes(router: Router, auth: OAuth2Auth): Unit {

    val oauth2 = OAuth2AuthHandler.create(vertx, auth)
    val authz = KeycloakAuthorization.create()

    router.route().handler(LoggerHandler.create())

    router.route("/api/*").handler(oauth2)

     router.route("/api/greet").handler {

      println(RoleBasedAuthorization.create("ad-admins").match(it.user()))

      authz.getAuthorizations(it.user()).await()
    }

  }

编译器抱怨 authz.getAuthorizations(it.user()).await() 关于 Suspension functions can be called only within coroutine body . 我做错什么了?
整个代码:

class MainVerticle : CoroutineVerticle() {

  private suspend fun initConfig(): JsonObject {
    val yamlConfigOpts = ConfigStoreOptions()
      .setFormat("yaml")
      .setType("file")
      .setConfig(JsonObject().put("path", "config.yaml"))

    val configRetrieverOpts = ConfigRetrieverOptions()
      .addStore(yamlConfigOpts)

    val configRetriever = ConfigRetriever.create(vertx, configRetrieverOpts)

    return configRetriever.config.await()
  }

  private suspend fun createJwtAuth(): OAuth2Auth =

    KeycloakAuth.discover(
      vertx,
      OAuth2Options()
        .setFlow(OAuth2FlowType.AUTH_CODE)
        .setClientID("svc")
        .setClientSecret("9d782e45-67e7-44b1-9b74-864f45f9a18f")
        .setSite("https://oic.dev.databaker.io/auth/realms/databaker")
    ).await()

  private suspend fun createRoutes(router: Router, auth: OAuth2Auth): Unit {

    val oauth2 = OAuth2AuthHandler.create(vertx, auth)
    val authz = KeycloakAuthorization.create()

    router.route().handler(LoggerHandler.create())

    router.route("/api/*").handler(oauth2)

    router.route("/api/greet").handler {

      println(RoleBasedAuthorization.create("ad-admins").match(it.user()))

      authz.getAuthorizations(it.user()).await()
    }

  }

  private suspend fun server(router: Router): HttpServer {
    val server = vertx.createHttpServer()

    return server.requestHandler(router)
      .listen(8080)
      .onSuccess {
        println("HTTP server started on port ${it.actualPort()}")
      }
      .onFailure {
        println("Failed to start the server. Reason ${it.message}")
      }
      .await()
  }

  override suspend fun start() {

    val router = Router.router(vertx)

    createRoutes(router, createJwtAuth())
    server(router)

  }

}

提示:我使用的是vertx4.0.0rc1

xghobddn

xghobddn1#

编译器因为 authz.getAuthorizations(it.user()).await() 不是在挂起函数中调用的:它是从vert.xWeb路由处理程序调用的。
你必须用 launch :

router.route("/api/greet").handler {
  println(RoleBasedAuthorization.create("ad-admins").match(it.user()))
  launch {
    authz.getAuthorizations(it.user()).await()
  }
}

给定此代码定义在 CoroutineVerticle ,协同程序将绑定到verticle上下文(以及在verticle的事件循环上调用的代码)。

相关问题