【发布时间】:2018-10-01 22:09:21
【问题描述】:
我有一个旧的 Scala/Akka Http 项目,我正在尝试对其进行简化和重构。我想知道是否有更好的方法来组织路线,并可能将它们分散到演员之间。这是我目前所拥有的(远非理想):
```
object MyAPI {
def props(): Props = Props(new MyAPI())
val routes = pathPrefix("api") {
pathPrefix("1") {
SomeActor.route //More routes can be appended here using ~
}
}
}
final class MyAPI extends Actor with ActorLogging {
implicit lazy val materializer = ActorMaterializer()
implicit lazy val executionContext = context.dispatcher
Http(context.system)
.bindAndHandleAsync(Route.asyncHandler(MyAPI.routes), MyHttpServer.httpServerHostName, MyHttpServer.httpServerPort)
.pipeTo(self)
override def receive: Receive = {
case serverBinding: ServerBinding =>
log.info(s"Server started on ${serverBinding.localAddress}")
context.become(Actor.emptyBehavior)
case Status.Failure(t) =>
log.error(t, "Error binding to network interface")
context.stop(self)
}
}
```
```
object SomeActor {
def props(): Props = Props[SomeActor]
val route = get {
pathPrefix("actor") {
pathEnd {
complete("Completed") //Is there a clean way 'ask' the actor below?
}
}
}
}
class SomeActor extends Actor with ActorLogging {
implicit lazy val executionContext = context.dispatcher;
override def receive: Receive = {
//receive and process messages here
}
```
所以,我的问题是 - 有没有一种简洁的方法来构建和重构路由,而不是将它们集中在一个大型路由定义中?我也许可以创建一个演员(路由器)的层次结构,主路由定义只是将它委托给路由器,随着我们在演员层次结构中的深入,我们逐渐添加更多细节。但是是否有一种或两种普遍接受的模式来组织路线?
【问题讨论】: