我有一个我想要开始的演员系统,直到特定的演员Destructor
收到ShutdownNow
消息。当它收到这样的消息时,它基本上执行相当于一个关闭钩子,关闭整个actor系统,然后父JVM进程/主线程关闭:这样的事情:
class MyApp {
static void main(String[] args) {
// Do some stuff before starting the actor system.
ActorSystem actorSystem = ActorSystem.create(“myapp-actorsys”)
ActorRef initializer = actorSystem.actorOf(Props.create(Initializer) “initializer”)
Inbox inbox = Inbox.create(actorSystem)
inbox.send(initializer, new Initialize())
// Now the actor system is initialized and is running
// Maybe its processing data off a message broker, etc.
// Here I’d like to wait until the actor system shuts down (see Destructor below)
while(actorSystem.isRunning()) { }
// Now do some final tasks.
} // <- end of main thread/parent JVM process
}
class Destructor extends UntypedActor {
@Override
void onReceive(Object msg) {
if(msg instanceof ShutdownNow) {
// Shut down the actor system such that actorSystem.isRunning()
// will return true.
}
}
}
这里的想法是父JVM进程保持活动状态,除非被底层操作系统(sigkill等)中断或 actor系统内部的某些信号向适当的信号发出ShutdownNow
消息演员。
如何实施?
答案 0 :(得分:1)
不知道您使用的确切设置:
Java进程不会停止,直到你的actor系统停止。因此,您无需执行任何操作,只需从Destructor Actor发送shutdown命令。
以下代码适用于我(包括使用actor停止进程内部以及使用kill从外部停止进程):
import java.util.concurrent.TimeUnit;
import scala.concurrent.duration.Duration;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
public class MyApp {
public static void main(String[] args) {
// Do some stuff before starting the actor system.
System.out.println("Start Actor System");
ActorSystem actorSystem = ActorSystem.create("myapp-actorsys");
ActorRef destructor = actorSystem.actorOf(Props.create(Destructor.class));
//Java process won't shut down before actor system stops
//Send message after timeout to stop system
actorSystem.scheduler().scheduleOnce(Duration.create(10, TimeUnit.SECONDS),
destructor, new ShutdownNow(), actorSystem.dispatcher(), null);
}
public static class Destructor extends UntypedActor {
public Destructor() {
}
@Override
public void onReceive(Object msg) {
if(msg instanceof ShutdownNow) {
//Shutdown system to stop java process
System.out.println("Stop Actor System");
getContext().system().shutdown();
}
}
}
public static class ShutdownNow {
}
}