Akka classic - 发送自定义 class 消息类型

Akka classic - sending custom class message types

我正在尝试遵循在 Akka actor 之间发送消息并阅读以下内容的最佳实践:

https://github.com/akka/akka/blob/v2.6.15/akka-docs/src/test/java/jdocs/actor/ActorDocTest.java#L101-L129

https://doc.akka.io/docs/akka/current/actors.html

似乎最好的做法是定义一个包含要发送的消息的静态 class。

通过阅读文档,我定义了以下内容:

import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.persistence.AbstractPersistentActor;

class RecoveryActor extends AbstractPersistentActor {

    public static class Msg1 {}
    public static class Msg2 {}

    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

    /**
     * Handler that will be called on recovery.
     * @return
     */
    @Override
    public Receive createReceiveRecover() {
        return receiveBuilder()
                .match(Msg1.class, this::receiveMsg1)
                .match(Msg2.class, this::receiveMsg2)
                .build();
    }

    private void receiveMsg1(Msg1 msg) {
        log.info("in receive message 1");
    }

    private void receiveMsg2(Msg2 msg) {
        log.info("in receive message 2");
    }

    /**
     * The normal receive method.
     * @return
     */
    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(String.class, s -> s.equals("cmd"), s -> persist("evt", this::handleEvent))
                .build();
    }

    private void handleEvent(String event) {
        System.out.println("in handle event");
    }

    @Override
    public String persistenceId() {
        return "simple-accountant"; //best practice, the id should be unique.
    }

}

但我不确定如何使用 Msg1Msg2

发送消息

我定义了一个新的 class 来发送消息 :

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;

public class ActorMessaging {

    public static void main(String args[]){
        final ActorSystem system = ActorSystem.create("example");
        final ActorRef actor = system.actorOf(Props.create(RecoveryActor.class));

        actor.tell(RecoveryActor.Msg1);

    }
}

但它因编译器错误而失败:

java: cannot find symbol
  symbol:   variable Msg1
  location: class recoverydemo.RecoveryActor

如何向 Msg1 类型的 Actor 发送消息?

这是在参与者之间发送消息的最佳实践,将消息包装在自定义 class 中吗?

actor.tell 正在接受对象。 RecoveryActor.Msg1 不是那个,它甚至不是 class 参考。像这样尝试发送 Msg1 的实例怎么样:

actor.tell(new RecoveryActor.Msg1(), actorRef)

为了与远程演员“交谈”,您首先需要获得对它的引用。这通常由 ActorSystem

完成

我犯了一个愚蠢的错误。我覆盖了不正确的方法。我应该改写 createReceive :

    public Receive createReceive() {

        return receiveBuilder()
                .match(RecoveryActor.Msg1.class, this::receiveMsg1)
                .match(Msg2.class, this::receiveMsg2)
                .build();
        
//        return receiveBuilder()
//                .match(String.class, s -> s.equals("cmd"), s -> persist("evt", this::handleEvent))
//                .build();
    }