简体   繁体   English

Akka Java-动态创建递归子角色?

[英]Akka Java - Creating recursive child actors on the fly?

It is my understanding that the onReceive can only be executed by one thread at any given point in time. 据我了解,onReceive只能在任何给定的时间点由一个线程执行。

Let's say I have an untyped actor defined like this: 假设我有一个无类型的actor定义如下:

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;


public class ExampleActor extends UntypedActor {

     private ActorRef databaseActor;


    @Override
    public void preStart() {
       ActorRef databaseActor = getContext().system().actorOf(Props.create(DatabaseActor.class));
    }


    @Override
    public void onReceive(Object message) throws Exception {

        if (message.equals("start")) {
            // spawn a child actor of myself!
            ActorRef child = getContext().actorOf(Props.create(ExampleActor.class));
            databaseActor.tell("fetch", child);
        }

        if (message.equals("dbresponse")) {
           // just log the repsonse here!
        }

        if (message.equals("something else")) {
           // possibly mutate state
        }


   }
}

I essentially want to use Akka without using futures. 我本质上是想使用Akka而不使用期货。 At the same time, I want my actors to NOT block as much as possible. 同时,我希望我的演员不要尽可能多地阻止。 Is it OK to spawn recursive child actors in my onReceive, soley for handling specific messages from other actors? 是否可以在我的onReceive,soley中生成递归子角色以处理来自其他角色的特定消息?

Essentially in my "if (message.equals("dbresponse"))", I want to just log a DB response and not mutate state in my ExampleActor. 本质上,在我的“ if(message.equals(“ dbresponse”))”中,我只想记录数据库响应,而不是在ExampleActor中更改状态。

Will this approach work? 这种方法行得通吗? What are the consequences of creating actors on the fly like this? 像这样即时创建演员的后果是什么?

You are doing it exactly right, this is how the Actor Model foresees handling of actor interactions. 您做的完全正确,这是Actor模型预见到Actor交互处理的方式。 Using the ask pattern does something which is effectively the same (but an optimized form of single-reply actor is spawned instead), so if you do not want to use Futures this is the way to opt out. 使用ask模式可以做的事情实际上是相同的(但是会生成优化形式的单答复演员),因此,如果您不想使用期货,这是退出的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM