我有一个扩展App的对象,其中我创建了Actor系统和Actor物化器,并且还在给定的actor系统下创建了actor。
record_bytes
现在UserRoutes包含所有路由
object QuickstartServer extends App with UserRoutes {
implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
implicit val materializer: ActorMaterializer = ActorMaterializer()
val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")
lazy val routes: Route = userRoutes
Http().bindAndHandle(routes, "localhost", 8080)
}
现在我的问题是Actor系统和在QuickstartServer中创建的trait UserRoutes extends JsonSupport {
implicit def system: ActorSystem
lazy val log = Logging(system, classOf[UserRoutes])
def userRegistryActor: ActorRef
lazy val userRoutes: Route =
pathPrefix("users") {
concat(
pathEnd {
concat(
get {
val users: Future[Users] =
(userRegistryActor ? GetUsers).mapTo[Users]
//Remaining code
actor如何注入到路由文件中?
您可以在此处https://developer.lightbend.com/guides/akka-http-quickstart-scala/backend-actor.html
中找到完整的代码答案 0 :(得分:3)
在特征的开头,您可以看到这两个声明:
implicit def system: ActorSystem
def userRegistryActor: ActorRef
这两个是trait中的抽象声明,这意味着trait的实现必须提供这两个。
使用以下两个声明,这就是对象中发生的事情:
implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")
相当一部分开发人员建议通过添加override关键字来使这种实现更加明确,例如:
override implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
override val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")