我尝试遵循在Akka演员之间发送消息的最佳实践,并阅读以下内容:
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
最好的做法似乎是定义一个包含要发送的消息的静态类。
通过阅读文档,我定义了以下内容:
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.
}
}
但我不确定如何使用Msg1
和Msg2
发送消息
我定义了一个新类来发送消息:
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
的执行元发送消息?
这是在参与者之间发送消息的最佳实践吗?将消息 Package 在自定义类中?
2条答案
按热度按时间qhhrdooz1#
actor.tell
正在接受对象。RecoveryActor.Msg1
不是这样的,它甚至不是类引用。尝试发送Msg1
的示例如何,如下所示:为了与远程参与者“对话”,首先需要获得对它的引用。
oalqel3c2#
我犯了一个愚蠢的错误。我覆盖了不正确的方法。我应该覆盖
createReceive
: