问题
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
?
回答1:
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(_ ~ _)
来源:https://stackoverflow.com/questions/36247381/how-to-aggregate-akka-http-routes-using-a-trait