如何使用trait聚合akka-http路由? [英] How to aggregate akka-http routes using a trait?

查看:206
本文介绍了如何使用trait聚合akka-http路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 对象SMController {
def aggregateRoutes(actorSystem:ActorSystem):List [Route] = {
val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
val reflections = new Reflections(com.example.api)
val子类= reflections.getSubTypesOf(classOf [Routable])
val routesList = new ListBuffer [Route]()

(i< - 子类){
val模块= runtimeMirror.staticModule(i.getName)
val obj = runtimeMirror.reflectModule(module)
val someTrait:Routable = obj.instance.asInstanceOf [Routable]
routesList + = someTrait.getAllRoutes actorSystem)
}

routesList.toList
}
}

显然上面的代码不起作用的项目列表不能传递给 Http()。bindAndHandle



所以我的问题是,怎么可以我解析列表[路由] 到一个 Http()。bindAndHandle 接受或如何动态加载来自子类的路由可路由

解决方案

foldLeft:
我已经设法折叠路由并合并所有路由,如下所示:

  val routes = SMController.aggregateRoutes系统)
val bindingFuture = Http()。bindAndHandle(
routes.tail.foldLeft(routes.head)((a,b)=> a〜b),localhost,8080)

reduceLeft: / p>

  routes.reduceLeft(_〜_)


I am trying to aggregate routes using a trait at runtime, so far I have

object SMController {
  def aggregateRoutes(actorSystem: ActorSystem): List[Route] = {
    val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
    val reflections = new Reflections("com.example.api")
    val subclasses = reflections.getSubTypesOf(classOf[Routable])
    val routesList = new ListBuffer[Route]()

    for (i <- subclasses) {
      val module = runtimeMirror.staticModule(i.getName)
      val obj = runtimeMirror.reflectModule(module)
      val someTrait: Routable = obj.instance.asInstanceOf[Routable]
      routesList += someTrait.getAllRoutes(actorSystem)
    }

    routesList.toList
  }
}

obviously above code doesn't work as the List of items cannot be passed to Http().bindAndHandle.

So my question is, how can I parse the List[Routes] to a Http().bindAndHandle accepts or how can I dynamically load routes from subclasses of Routable?

解决方案

foldLeft: I have managed to foldLeft the routes and coalesce all the routes, as follows

val routes = SMController.aggregateRoutes(system)
val bindingFuture = Http().bindAndHandle(
        routes.tail.foldLeft(routes.head)((a, b) => a ~ b), "localhost", 8080)

reduceLeft:

routes.reduceLeft(_ ~ _)

这篇关于如何使用trait聚合akka-http路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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