【问题标题】:Akka HTTP: How to split routes with actorsAkka HTTP:如何使用参与者拆分路由
【发布时间】: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

  }

```

所以,我的问题是 - 有没有一种简洁的方法来构建和重构路由,而不是将它们集中在一个大型路由定义中?我也许可以创建一个演员(路由器)的层次结构,主路由定义只是将它委托给路由器,随着我们在演员层次结构中的深入,我们逐渐添加更多细节。但是是否有一种或两种普遍接受的模式来组织路线?

【问题讨论】:

    标签: scala akka akka-http


    【解决方案1】:

    我想建议您根据您可以拥有任意数量的演员的功能,但创建一个监督演员来监视每个子演员。并且所有的监督策略都应该写入监督者本身,你要发送给演员的所有消息都应该由监督者转发。

    一旦您从端点获取数据,可能会通过 get 或 post 方法将数据放入 someRequest 案例类。然后将其发送到一些 handleReq() 方法。然后根据功能进行处理。

    您可以像这样构建项目。 源/ 演员//all the actors will be in this package

    型号// all the case classes and constants

    repo// all the db related function you can do here

    service// all your routes and endPoint functions

    现在您可以拥有包 util,其中您可以放置​​所有实用程序 trait,这些特性将被任何参与者使用,或者服务可能是您有很多验证,您可以拥有一个名为验证器的包。

    结构取决于您的业务。我认为这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 1970-01-01
      • 2017-08-27
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多