1.创建Actor
只要继承UntypedActor类,重写onReceive(message)方法,这个方法主要是接收Actor发来的信息。
2. Props配置类
对创建角色确认选项,
Props.create(MyActor.class);
final ActorRef myActor =system.actorOf(Props.create(MyUntypedActor.class),
"myactor");
final ActorRef child = getContext().actorOf(Props.create(MyUntypedActor.class), "myChild");
Inbox
final Inbox inbox = Inbox.create(system);
inbox.send(target, "hello");
assert inbox.receive(Duration.create(1, TimeUnit.SECONDS)).equals("world");
注册一个监视器
public class WatchActor extends UntypedActor {
final ActorRef child = this.getContext().actorOf(Props.empty(), "child");
{
this.getContext().watch(child); // <-- the only call needed for registration
}
ActorRef lastSender = getContext().system().deadLetters();
@Override
public void onReceive(Object message) {
if (message.equals("kill")) {
getContext().stop(child);
lastSender = getSender();
} else if (message instanceof Terminated) {
final Terminated t = (Terminated) message;
if (t.getActor() == child) {
lastSender.tell("finished", getSelf());
}
} else {
unhandled(message);
}
}
}
在正确启动角色之后,preStart方法被调用,终止一个角色之后,其postStop钩子被调用时。即送到已终止角色的信息将被重定向到ActorSystem的deadLetters。
识别角色
每个角色都有一个唯一的逻辑路径,它有一个物理路径
通过角色选择集actorSelection,其中指定的路径被解释为一个java.net.URI,
一个角色选择集的路径元素可以包含通配符,允许消息额广播到该选择集:
getContext().actorSelection("/user/serviceB/worker*");
为了获得ActorSelection的ActorRef,发送一个消息到AcorSelection,AcorSelection有一个内置的识别消息(所有Actor都理解并且自动回复一个包含ActorRef的ActorIdentity消息。)。这个消息被Actor特殊处理。
public class Follower extends UntypedActor {
final String identifyId = "1";
{
ActorSelection selection =
getContext().actorSelection("/user/another");
selection.tell(new Identify(identifyId), getSelf());
}
ActorRef another;
final ActorRef probe;
public Follower(ActorRef probe) {
this.probe = probe;
}
@Override
public void onReceive(Object message) {
if (message instanceof ActorIdentity) {
ActorIdentity identity = (ActorIdentity) message;
if (identity.correlationId().equals(identifyId)) {
ActorRef ref = identity.getRef();
if (ref == null)
getContext().stop(getSelf());
else {
another = ref;
getContext().watch(another);
probe.tell(ref, getSelf());
}
}
} else if (message instanceof Terminated) {
final Terminated t = (Terminated) message;
if (t.getActor().equals(another)) {
getContext().stop(getSelf());
}
} else {
unhandled(message);
}
}
}
远程角色地址也可以查找
getContext().actorSelection("akka.tcp://app@otherhost:1234/user/serviceB");