如何传递FSM Actor的ActorRef以初始化另一个Actor?附代码示例
在Akka中传递FSM Actor的ActorRef初始化另一个Actor
咱们先看你已经实现的MyMainActor代码,这里我帮你修正了构造函数里的一个大小写小问题(Myclass改成MyClass):
public class MyMainActor extends AbstractActor { MyClass myclass; ActorRef myFsm; public static Props props(MyClass myclass, ActorRef myfsm) { return Props.create(MyMainActor.class, () -> new MyMainActor(myclass, myfsm)); } public MyMainActor(MyClass myclass, ActorRef myfsm) { this.myclass = myclass; this.myfsm = myfsm; } @Override public Receive createReceive() { // 在这里处理消息逻辑 return receiveBuilder() // 示例:处理消息并和FSM Actor交互 .match(SomeMessage.class, msg -> myFsm.tell(new FsmMessage(msg), getSelf())) .build(); } }
接下来我帮你补全测试代码的完整示例,展示如何先创建FSM Actor,再把它的ActorRef传入MyMainActor完成初始化:
new TestKit(system) {{ // 先创建你的FSM Actor实例 ActorRef myFsmActor = system.actorOf(MyFsmActor.props(), "test-fsm-actor"); // 初始化MyClass实例 MyClass testMyClass = new MyClass(); // 创建MyMainActor,传入MyClass和FSM Actor的ActorRef ActorRef myMainActor = system.actorOf(MyMainActor.props(testMyClass, myFsmActor), "test-main-actor"); // 添加测试逻辑:给MyMainActor发消息,验证它和FSM Actor的交互 myMainActor.tell(new SomeMessage("test content"), getRef()); // 等待并验证预期的响应 expectMsgClass(ExpectedResponse.class); }};
几个需要注意的小细节:
- 确保你的FSM Actor(比如
MyFsmActor)也有标准的props()方法来创建实例,和MyMainActor的实现方式保持一致 - 在测试中,通过
system.actorOf()创建FSM Actor后,直接拿到它的ActorRef,再传递给MyMainActor的props()方法就能完成初始化 - 如果需要在
MyMainActor内部和FSM Actor交互,直接使用保存的myFsm引用发送消息即可
内容的提问来源于stack exchange,提问作者user_mda
相关产品推荐
相关产品推荐

