我实现了一个自定义机制,用于将Akka与Spring集成为DI框架,在该框架中,我将ActorSystem注册为一个单例作用域的bean:
@Configuration
internal open class SpringAkkaConfiguration
{
@Bean
open fun actorSystem(@Value("\${akka.tcp.port}") akkaTcpPort: Int): ActorSystem
{
val config = ConfigFactory
.defaultApplication()
.withValue("akka.remote.netty.tcp.port", ConfigValueFactory.fromAnyRef(akkaTcpPort))
.withValue("akka.remote.netty.tcp.hostname", ConfigValueFactory.fromAnyRef("localhost"))
.withValue("akka.loglevel", ConfigValueFactory.fromAnyRef("WARNING"))
return ActorSystem.create("system", config)
}
}
@Component
internal class SpringActorSystem(private val actorSystem: ActorSystem,
private val beanFactory: BeanFactory) : SpringAkka
{
override fun announce(actorClass: Class<out Actor>): ActorRef
{
val props = Props.create(SpringIndirectActorProducer::class.java, beanFactory, actorClass)
return actorSystem.actorOf(props, actorClass.simpleName)
}
}
,并在其中使用自定义批注@Actor创建了两个“经理”演员,这表明它的作用域为“原型”:
@Target(AnnotationTarget.CLASS, AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@Component
@Scope("prototype")
annotation class Actor
@Actor
internal class FirstManager(private val connectionService: ConnectionService) : AbstractActor()
{
override fun createReceive(): Receive = receiveBuilder().build()
}
@Actor
internal class SecondManager(private val connectionService: ConnectionService) : AbstractActor()
{
override fun createReceive(): Receive = receiveBuilder().build()
}
每个演员都是从IoC挑选出来的,并且还是一个孩子,并在ActorSystem中进行了注册,直到我想到了为管理者创建子演员的想法,一切工作都很好,所以层次结构如下所示:
-system
- FirstManager
-firstchild
-secondchild
-SecondManager
-first-child
-second-child
将以下子级注册给每个管理者而不是ActorSystem本身来建立上述层次结构的最佳解决方案是什么?每个儿童演员都依赖于其他服务,我希望有可能毫不费力地注入他们。示例:
@Actor
internal class ChildActor(private val anotherService: AnotherService): AbstractActor()
{
override fun createReceive(): Receive = receiveBuilder().build()
}