【问题标题】:How to implement a REST API with akka typed actor system如何使用 akka 类型化的 Actor 系统实现 REST API
【发布时间】:2020-09-26 02:58:37
【问题描述】:

我正在尝试使用带有 akka-http 的 scala 启动 REST API。我是 akka 和 actor 模型范例的新手,所以我想实现一个类型化的 actor 系统,但我得到了这个 sbt 编译错误:

could not find implicit value for parameter system: akka.actor.ActorSystem (implicit ActorRefFactory required: if outside of an Actor you need an implicit ActorSystem, inside of an actor this should be the implicit ActorContext)
[error]     val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

知道这里发生了什么吗?这是我基于 akka 文档中的示例的代码:

object FeedAggregatorServer {
  def apply(): Behavior[Nothing] =
    Behaviors.setup[Nothing](context => new FeedAggregatorServer(context))
}

class FeedAggregatorServer(context: ActorContext[Nothing]) extends AbstractBehavior[Nothing](context) {
  context.log.info("Application started")

  override def onMessage(msg: Nothing): Behavior[Nothing] = {
    // No need to handle any messages
    Behaviors.unhandled
  }

  override def onSignal: PartialFunction[Signal, Behavior[Nothing]] = {
    case PostStop =>
      context.log.info("Application stopped")
      this
  }

}

object FeedAggregatorApp {

  def main(args: Array[String]): Unit = {
    ActorSystem[Nothing](FeedAggregatorServer(), "FeedAggregatorServer")

    val route =
      concat (
        path("") {
          complete("Hello, World!")
        },
        path("feed") {
          complete("Hello!")
        }
      )

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done
  }

}

路由应该在 FeedAggregatorServer 中,或者...?

【问题讨论】:

标签: scala api rest http akka


【解决方案1】:

在创建 akka-http 服务器时,您需要定义一个 implicit akka.actor.ActorSystem(注意,需要一个经典的 Actor 系统,尽管这将在 akka-http 的未来版本中改变)。您可以了解更多关于interoperation between classic and typed actor systems in the akka docs(如https://stackoverflow.com/users/4268228/shankar-shastri 所述)的信息。

根据您的代码,您需要隐式提供经典的演员系统,如下所示:

// you could move this to your other imports
import akka.actor.typed.scaladsl.adapter._

val typedSystem = ActorSystem[Nothing](FeedAggregatorServer(), "FeedAggregatorServer")
implicit val classicSystem = typedSystem.toClassic
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-15
    • 2013-02-06
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多